在 Python 中,可以使用字符串的'replace()'方法来替换换行符。具体方法如下:

  1. 将字符串中的换行符替换为其他字符,如空格:
string = 'hello\nworld'
new_string = string.replace('\n', ' ')
print(new_string)  # 输出: 'hello world'
  1. 将字符串中的换行符删除:
string = 'hello\nworld'
new_string = string.replace('\n', '')
print(new_string)  # 输出: 'helloworld'

需要注意的是,字符串是不可变对象,'replace()'方法返回的是一个新的字符串,原字符串并没有改变。如果想要在原字符串上修改,可以重新赋值:

string = 'hello\nworld'
string = string.replace('\n', ' ')
print(string)  # 输出: 'hello world'
Python 字符串替换换行符:方法和示例

原文地址: https://www.cveoy.top/t/topic/mzoD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录