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)
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.
2条答案
按热度按时间yzckvree1#
以下是一些选项
5uzkadbs2#
可以使用
str.translate()
删除'\n'
s或任何其他字符。请为translate()
提供一个dict,该dict将要替换的字符的Unicode序数Map到要替换它们的字符。在您的情况下:来自'help(字符串翻译):
更新:我并不是说
str.translate()
是解决这个问题的最佳或最合适的方案,只是一个选项,我认为str.replace()
是自然的解决方案。