Python在字符“X”后的字符串中插入换行符

2024-09-21 11:48:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在每次出现字符“X”后插入换行符的python语法是什么?下面给了我一个没有split属性错误的list对象

for myItem in myList.split('X'):
  myString = myString.join(myItem.replace('X','X\n'))

Tags: 对象infor属性错误语法字符replace
3条回答
myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))

列表没有split方法(如错误所述)。

假设myList是一个字符串列表,并且您希望在每个字符串中用'X\n'替换'X',则可以使用列表理解:

new_list = [string.replace('X', 'X\n') for string in myList]

Python 3.X

myString.translate({ord('X'):'X\n'})

translate()允许dict,因此,一次可以替换多个不同的字符。

为什么要在replace()之上translate()?检查translate vs replace

Python 2.7版

myString.maketrans('X','X\n')

相关问题 更多 >

    热门问题