【问题标题】:Ignoring or removing line breaks python [duplicate]忽略或删除换行符python [重复]
【发布时间】:2013-09-13 22:24:12
【问题描述】:

对于这个愚蠢的问题,我很抱歉,但我看过的答案似乎都没有解决这个问题。我想采用这样的多行字符串:

myString = """a
b
c
d
e"""

并得到一个看起来像或至少被解释为这样的结果:

myString = "abcde"

myString.rstrip()、myString.rstrip(\n) 和 myString.rstrip(\r) 在我打印这个小“abcde”测试字符串时似乎没有任何改变。我读过的其他一些解决方案涉及像这样输入字符串:

myString = ("a"
"b"
"c")

但是这个解决方案是不切实际的,因为我正在处理非常大的数据集。我需要能够复制数据集并将其粘贴到我的程序中,并让 python 删除或忽略换行符。

我输入错误了吗?有一个优雅的解决方案吗?提前感谢您的耐心等待。

【问题讨论】:

    标签: python string multiline


    【解决方案1】:

    使用replace 方法:

    myString = myString.replace("\n", "")
    

    例如:

    >>> s = """
    test
    test
    test
    """
    >>> s.replace("\n", "")
    'testtesttest'
    >>> s
    '\ntest\ntest\ntest\n' # warning! replace does not alter the original
    

    【讨论】:

    • 那个分号刺痛了我的眼睛。
    【解决方案2】:
    >>> myString = """a
    ... b
    ... c
    ... d
    ... e"""
    >>> ''.join(myString.splitlines())
    'abcde'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2023-02-02
      相关资源
      最近更新 更多