“ t”是带有文本的变量。您将看到一个“ s”变量,它是一个临时变量,只存在于主括号集的求值过程中(忘记了这些 lil python 东西的名称)
首先让我们设置“ t”变量,这样它就有了新的行:
>>> t='hi there here is\na big line\n\nof empty\nline\neven some with spaces\n \nlike that\n\n \nokay now what?\n'
注意,还有一种使用三重引号设置变量的方法
somevar="""
asdfas
asdf
asdf
asdf
asdf
""""
下面是我们在不打印的情况下看到它的样子:
>>> t
'hi there here is\na big line\n\nof empty\nline\neven some with spaces\n \nlike that\n\n \nokay now what?\n'
若要查看实际换行,请打印它。
>>> print t
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
命令删除所有空行(包括空格) :
所以有些换行只是换行,有些有空格所以看起来像新行
如果您想去除所有空白的外观行(如果它们只有换行或空格)
>>> print "".join([s for s in t.strip().splitlines(True) if s.strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
或者:
>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
.without strip new line here (stackoverflow cant have me format it in).
使用第2个示例(仅删除换行符)
>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
.without strip new line here (stackoverflow cant have me format it in).