Python 3.x 用Python删除\n字符
我有一个包含此“\n”字符的句子列表Python 3.x 用Python删除\n字符,python-3.x,string,Python 3.x,String,我有一个包含此“\n”字符的句子列表 [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties"), ...] 我尝试了以下代码: def remove_whitespace(sent_text): j=0 for i in sent_text: sent_text[j]=i.rstrip("\n") j+=1 remove_whitespace(sent_t
[("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties"), ...]
我尝试了以下代码:
def remove_whitespace(sent_text):
j=0
for i in sent_text:
sent_text[j]=i.rstrip("\n")
j+=1
remove_whitespace(sent_text)
但是\n字符没有消失。
有什么想法吗
感谢使用
str.split
和str.join
Ex:
data = [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties")]
for text in data:
text = "".join(text.split("\n"))
print(text)
Types of Third-Parties
Examples of third-parties
输出:
data = [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties")]
for text in data:
text = "".join(text.split("\n"))
print(text)
Types of Third-Parties
Examples of third-parties
一种快速解决方案是使用
str.replace
。
就你而言:
def删除空白(已发送文本):
j=0
对于我发送的文本:
已发送\u text[j]=i.replace(“\n”,”)
j+=1
您可以使用rstrip()函数
如果文本与\n或\r一起出现,text.rstrip()会将其删除。您也可以使用列表理解来删除这些不需要的项目
input_list = [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties")]
def expunge_unwanted_elements(input_variable):
cleaned = [item.replace('\n', ' ').strip() for item in input_variable]
# Do you want to remove the dashes? If so use this one.
# cleaned = [item.replace('\n', '').replace('-', ' ').strip() for item in input_variable]
return cleaned
print (expunge_unwanted_elements(input_list))
# outputs
['Types of Third - Parties', 'Examples of third - parties']
# or this output if you use the other cleaned in the function
['Types of Third Parties', 'Examples of third parties']
那么?i、 replace(“\n”,”)@SmartManoj thakns,您的方法将“\n”替换为一个空格,但我希望在
i.replace('\n','')时将其删除。