簡體   English   中英

python:在多行字符串中粘貼行

[英]python: paste lines in a multi-line string

假設我有一個多行字符串,其中行用\n符號分隔。 我可以選擇將這些行合並為一個冗長的字符串嗎? 我只有以下想法:

s = """Text line
another text line
and another long text line"""

s = s.replace('\n', '')
print(s)

這里有一些選項

s = """Text line
another text line
and another long text line"""

#option 1
s1 = s.replace('\n', ' ')

#option 2
s2 = s.split('\n')
s2= " ".join(s2)

#option 3
s3 = s.splitlines()
s3 = " ".join(s3)

#option 4
import re 
s4 = re.sub('\n', ' ', s)
print(s4) 

您可以使用str.translate()刪除'\n'或任何其他字符。 translate()提供一個 dict 映射 Unicode 要替換的字符的序號到要替換它們的字符。 在你的情況下:

s.translate({ord('\n'): None})

來自`幫助(str.translate):

Help on built-in function translate:

translate(table, /) method of builtins.str instance
    Replace each character in the string using the given translation table.
    
      table
        Translation table, which must be a mapping of Unicode ordinals to
        Unicode ordinals, strings, or None.
    
    The table must implement lookup/indexing via __getitem__, for instance a
    dictionary or list.  If this operation raises LookupError, the character is
    left untouched.  Characters mapped to None are deleted.

更新:我並不是說str.translate()是解決問題的最佳或最合適的方法,只是一個選項。 我認為str.replace()是這里的自然解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM