.strip(“\ n”)不从字符串中删除“\ n”

时间:2018-03-04 02:59:26

标签: python string strip

 def __init__(self, text):
     self.text = text.strip("\r").strip("\n").strip("\r").strip(" ")
     print("TEXT:"+text+";SELFTEXT:"+self.text)

text被输入为“http://thehill.com/homenews/senate/376515-jeff-flake-there-will-be-a-republican-challenger-to-trump-in-2020 \ r \ n” self.text仍然相同(不会移除\r\n)。

将此代码放在Shell for Python上时,它可以根据需要运行。 有什么想法吗?

编辑:当print语句更改为         打印( “REPR:” +再版(文本)+ “\ n文字:” +文本+ “; SELFTEISXT:” + self.text)

类似字符串的输出是:

REPR: 'http://thehill.com/homenews/senate/376548-lindsey-graham-war-with-north-korea-would-be-worth-it-in-the-long-run\r\n' TEXT:http://thehill.com/homenews/senate/376548-lindsey-graham-war-with-north-korea-would-be-worth-it-in-the-long-run \ r \ N; SELFTEISXT:http://thehill.com/homenews/senate/376548-lindsey-graham-war-with-north-korea-would-be-worth-it-in-the-long-run \ r \ n

2 个答案:

答案 0 :(得分:1)

试试这个:

text.replace("\r\n","")

答案 1 :(得分:0)

尝试使用原始字符串。我在"r"

中添加了replace(r"\r\n", "")

<强> EX:

text =  """http://thehill.com/homenews/senate/376515-jeff-flake-there-will-be-a-republican-challenger-to-trump-in-2020\r\n"""
print(text)
print(text.replace(r"\r\n", "").strip())

<强>输出:

http://thehill.com/homenews/senate/376515-jeff-flake-there-will-be-a-republican-challenger-to-trump-in-2020\r\n
http://thehill.com/homenews/senate/376515-jeff-flake-there-will-be-a-republican-challenger-to-trump-in-2020