如何从python中的字符串中删除所有类型的换行符或格式设置

2024-10-01 15:36:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道处理换行符、制表符的经典方法,。。是指向.strip()或.remove('\n','')。 但有时也有一些特殊情况下,这些方法是失败的

         'H\xf6cke\n\n:\n\nDie'.strip()

  gives: 'H\xf6cke\n\n:\n\nDie'

我怎样才能捕捉到这些必须逐一涵盖的罕见案例(例如,通过.remove('*','')?以上只是我遇到的一个例子。在


Tags: 方法情况remove制表符案例例子指向strip
3条回答

Strip文件:
返回带有前导和尾随的字符串S的副本 删除空白。 如果指定了字符而不是没有,则删除字符中的字符。在

这就是为什么它没有删除文本中的'\n'。在

如果要删除'\n'个可使用的匹配项

'H\xf6cke\n\n:\n\nDie'.replace('\n','')
Output: Höcke:Die
In [1]: import re

In [2]: text = 'H\xf6cke\n\n:\n\nDie'

In [3]: re.sub(r'\s+', '', text)
Out[3]: 'Höcke:Die'

\s:

Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched (but the flag affects the entire regular expression, so in such cases using an explicit [ \t\n\r\f\v] may be a better choice).

“+”

Causes the resulting RE to match 1 or more repetitions of the preceding RE.

如果不想导入任何内容,请使用replace

a = "H\xf6cke\n\n:\n\nDie"
print(a.replace("\n",""))

# Höcke:Die

相关问题 更多 >

    热门问题