我正在尝试从变量q
中删除换行符。
我是python的新手,并试图这样做,但这不起作用:
q.strip()
strip
删除字符串的最开始和最后处的空白(包括换行符(。它不会删除字符串中间的字符(即,如果在任何非空白字符之间,它们就不会被删除(。
您可以使用replace
将它们全部替换为空(删除它们(。
q = q.replace('n', '').replace('r', '')
此外,您可以同时使用.splitlines
和.join
列表:
string = "hellonworldn"
new_string = " ".join(string.splitlines()) # Splitlines returns a list so we need to join it together using .join
print(new_string)
输出:
hello
world
hello world