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

dauxcl2d  于 2022-12-15  发布在  Python
关注(0)|答案(2)|浏览(147)

假设我有一个多行字符串,其中各行用\n符号分隔,我有哪些选项可以将各行合并成一个长字符串?我只有以下想法:

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

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

yzckvree1#

以下是一些选项

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)
5uzkadbs

5uzkadbs2#

可以使用str.translate()删除'\n' s或任何其他字符。请为translate()提供一个dict,该dict将要替换的字符的Unicode序数Map到要替换它们的字符。在您的情况下:

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

来自'help(字符串翻译):

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()是自然的解决方案。

相关问题