在 Python 中从字符串中删除换行符可以使用哪些方式?

关注者
7
被浏览
43,668

5 个回答

在python中如果要在一段话中移除某个字符,常用的方法有好几种,今天我们就逐个说一下。

1、split()方法:分割后再拼接

这种方法是利用split()函数的指定某个字符进行分割,将一段话分成前后两个部分,分割后的2个字符串我们可以拼接起来形成一个新的字符串,代码示例:

>>> str = 'I am a student, I have learnt python for three years'
'I am a student, I have learnt python for three years'
>>> split_str = str.split('python')
>>> new_str = ""
>>> for line in split_str:
...     new_str += line
>>> print(new_str)
I am a student, I have learnt for three years

可以看到我们以 python 字符串进行分割,将分割后的2个字符串进行重新赋值到一个新字符串中,这样就形成了一个新的字符串,而 python 这个字符就被从源字符串删除掉了,这就实现了开始我们说的移除字符串的功能,那从这个代码看还是有点麻烦,因为既然是字符串拼接,我们还可以选择其他方式,比如 join() 函数,可以更方便的让我们下用 join() 的方式实现下:

>>> str = 'I am a student, I have learnt python for three years'
'I am a student, I have learnt python for three years'
>>> split_str = str.split('python')
>>> new_str = "".join(split_str)
>>> print(new_str)