string - 在 Python 2.7 中替换字符串中的 '\n'

标签 string replace newline python-2.x

这是我的文件.txt:

Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;

我想将换行符 '\n' 转换为 ' $ '。我刚刚用过:

f = open(fileName)
text = f.read()      
text = text.replace('\n',' $ ')
print(text)

这是我的输出:

$ Spam Egg Sausage and Spam;

我的输出必须是这样的:

Egg and Bacon; $ Egg, sausage and Bacon $ Egg ...

我做错了什么?我正在使用 #-*- 编码:utf-8 -*-

谢谢。

最佳答案

您的换行符可能表示为 \r\n。为了替换它们,您应该这样做:

text.replace('\r\n', ' $ ')

对于同时适用于类 UNIX 系统(使用 \n)和 Windows(使用 \r\n)的可移植解决方案,您可以替换为使用正则表达式的文本:

>>> import re
>>> re.sub('\r?\n', ' $ ', 'a\r\nb\r\nc')
'a $ b $ c'
>>> re.sub('\r?\n', ' $ ', 'a\nb\nc')
'a $ b $ c'

关于string - 在 Python 2.7 中替换字符串中的 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251378/

相关文章:

jquery - Html/Css - 用点替换单行或多行

php - 换行符加解密显示在网站上

javascript - 如何在 React Native 中的 <Text> 组件中插入换行符?

vim - 使用 vim 处理文本文件中的\r\n ^M ​​^@

r - 在字符串 R 中创建数字序列

php - 如何验证这种格式的字符串 : p[1 or more numbers]?

php - 使用php将数字转换为utf-8 unicode

string - 使用 DOS 中断 MASM 获取字符串输入和显示输入

php - 使用一个过滤器清理 [code] 标签外部的内容,并使用另一个过滤器清理 [code] 标签内部的内容

python - 如何随机替换嵌套列表中的特定元素?