【问题标题】:Delete /n at end of a String (Python) [duplicate]在字符串末尾删除 /n(Python)[重复]
【发布时间】:2016-03-21 00:30:28
【问题描述】:

如何删除字符串末尾的/n 换行符?

我正在尝试从.txt 文件中读取两个字符串,并希望在“清除”字符串后使用os.path.join() 方法对其进行格式化。

在这里你可以看到我对虚拟数据的尝试:

content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']

for string in content:
    print(string)
    if string.endswith('\\\n'):
        string = string[0:-2]

print(content)

【问题讨论】:

  • 我认为您正在尝试修改迭代器而不是内容,此外这可以满足您的要求:[x.rstrip('\n') for x in content]

标签: python


【解决方案1】:

您无法像尝试那样更新字符串。 Python 字符串是不可变的。每次更改字符串时,都会创建新实例。但是,您的列表仍然引用旧对象。因此,您可以创建一个新列表来保存更新的字符串。要去除换行符,您可以使用 rstrip 函数。看看下面的代码,

content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []
for string in content:
    print(string)
    updated.append(string.rstrip())

print(updated)

【讨论】:

    【解决方案2】:

    您可以使用rstrip 函数。它会从字符串中修剪任何“空”字符串,包括\n,如下所示:

    >>> a = "aaa\n"
    >>> print a
    aaa
    >>> a.rstrip()
    'aaa'
    

    【讨论】:

      【解决方案3】:

      要仅删除 \n,请使用:

      string = string.rstrip('\n')
      

      【讨论】:

        【解决方案4】:

        当您执行 string[0:-2] 时,实际上是从末尾删除 2 个字符,而 \n 是一个字符。

        尝试:

        content = map(lambda x: x.strip(), content)
        

        【讨论】:

          猜你喜欢
          • 2014-05-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-19
          • 1970-01-01
          • 2014-02-15
          相关资源
          最近更新 更多