[英]How to remove white space from multi line string value in Python without using regular expression
[英]Python: use regular expression to remove the white space from all lines
^(\\s+)
仅从第一行中删除空格。 如何从所有行中删除前面的空格?
Python的正则表达式模块不默认为多行^
匹配 ,因此您需要明确指定该标志。
r = re.compile(r"^\s+", re.MULTILINE)
r.sub("", "a\n b\n c") # "a\nb\nc"
# or without compiling (only possible for Python 2.7+ because the flags option
# didn't exist in earlier versions of re.sub)
re.sub(r"^\s+", "", "a\n b\n c", flags = re.MULTILINE)
# but mind that \s includes newlines:
r.sub("", "a\n\n\n\n b\n c") # "a\nb\nc"
也可以在模式中包含内联标志:
re.sub(r"(?m)^\s+", "", "a\n b\n c")
更简单的解决方案是避免使用正则表达式,因为原始问题非常简单:
content = 'a\n b\n\n c'
stripped_content = ''.join(line.lstrip(' \t') for line in content.splitlines(True))
# stripped_content == 'a\nb\n\nc'
@AndiDog在他(目前接受的)答案中承认,它连续播出了新的排名。
这是如何解决这个缺陷,这是因为\\n
是两个空格和一个行分隔符。 我们需要做的是创建一个仅包含除换行符之外的空白字符的重新类。
我们想要whitespace and not newline
,它们不能直接在re class中表达。 让我们重写那not not (whitespace and not newline)
即not(not whitespace or not not newline
(谢谢, 奥古斯都 ),即not(not whitespace or newline)
即re
表示法中的[^\\S\\n]
。
所以:
>>> re.sub(r"(?m)^[^\S\n]+", "", " a\n\n \n\n b\n c\nd e")
'a\n\n\n\nb\nc\nd e'
你可以尝试使用strip()
如果你想要删除正面和背面,或者如果你想要删除前面的lstrip()
>>> s=" string with front spaces and back "
>>> s.strip()
'string with front spaces and back'
>>> s.lstrip()
'string with front spaces and back '
for line in open("file"):
print line.lstrip()
如果你真的想使用正则表达式
>>> import re
>>> re.sub("^\s+","",s) # remove the front
'string with front spaces and back '
>>> re.sub("\s+\Z","",s)
' string with front spaces and back' #remove the back
nowhite = ''.join(mytext.split())
没有空格会像你问的那样(一切都是一个字)。 更有用的通常是用' '
或'\\n'
加入所有内容以分别保留单词。
在大多数情况下,您实际上并不需要正则表达式。 如果您只想删除多行的常见缩进,请尝试使用textwrap
模块:
>>> import textwrap
>>> messy_text = " grrr\n whitespace\n everywhere"
>>> print textwrap.dedent(messy_text)
grrr
whitespace
everywhere
请注意,如果缩进是不规则的,则会保持:
>>> very_messy_text = " grrr\n \twhitespace\n everywhere"
>>> print textwrap.dedent(very_messy_text)
grrr
whitespace
everywhere
你必须使用re.MULTILINE选项:
re.sub("(?m)^\s+", "", text)
“(?m)”部分启用多行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.