有没有一种Python函数可以从字符串中删除空白(空格和制表符)?
这样,给定输入" \t example string\t "
就会变成"example string"
。
有没有一种Python函数可以从字符串中删除空白(空格和制表符)?
这样,给定输入" \t example string\t "
就会变成"example string"
。
txt="potatoes"
print("I love ",txt,"",sep="")
这将打印: 我喜欢土豆。
而不是: 我喜欢土豆。
在您的情况下,因为您想要摆脱 \t,请使用 sep="\t"。
尝试翻译
>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
这个方法与Qt的QString :: trimmed()方法非常相似,它会删除前导和尾随空格,同时保留内部空格。
但是,如果您想要像Qt的QString :: simplified()方法一样不仅删除前导和尾随空格,而且还将所有连续的内部空格“压缩”为一个空格字符,您可以使用.split()
和" ".join
的组合,就像这样:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
通常,我使用以下方法:
>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
myStr = re.sub(i, r"", myStr)
>>> myStr
'Hi Stack Over flow'
这将从字符串的开头和结尾删除所有空格和换行符:
>>> s = " \n\t \n some \n text \n "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"
s.strip()
可以完全做到这一点? - Ned Batchelders.strip()
只处理初始的空格,但不处理在删除其他不需要的字符后“发现”的空格。请注意,这将删除甚至是最终前导\n
之后的空格。 - Rafes.strip()
产生的结果与你的正则表达式完全相同。 - Ned Batchelder
string.whitespace
中。 - John Fouhy