【问题标题】:Removing newline in the middle of a string, with replace()使用 replace() 删除字符串中间的换行符
【发布时间】:2022-07-21 20:35:09
【问题描述】:

看了这个Removing continuation characters in the middle of a string in Python 和关于strip() 和replace() 的文档后,我非常困惑为什么我不能在字符串中间删除这个换行符? 我考虑到 \ 是字符串文字中的转义字符,它仍然不适用于原始字符串。我错过了什么?

import re

data="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
data2="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

result = data.replace(r'\n', "")
result2 =data2.replace('\\n', "") 
print(result)
print(result2)

【问题讨论】:

    标签: python string replace


    【解决方案1】:

    您正在尝试删除文字字符串\n,而不是换行符。当您设置result 时,您使用的是原始字符串,因此不会处理转义序列。当你设置result2 时,你会转义反斜杠,所以它不是转义序列。

    只需使用'\n' 换行即可。

    data="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
    data2="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
    
    result = data.replace('\n', "")
    result2 =data2.replace('\n', "") 
    print(result)
    print(result2)
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      相关资源
      最近更新 更多