哪个命令用于从字符串中删除换行符



我正在尝试从变量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

最新更新