2024-09-21 11:48:12 发布
网友
在每次出现字符“X”后插入换行符的python语法是什么?下面给了我一个没有split属性错误的list对象
for myItem in myList.split('X'): myString = myString.join(myItem.replace('X','X\n'))
myString = '1X2X3X' print (myString.replace ('X', 'X\n'))
列表没有split方法(如错误所述)。
split
假设myList是一个字符串列表,并且您希望在每个字符串中用'X\n'替换'X',则可以使用列表理解:
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,因此,一次可以替换多个不同的字符。
translate()
为什么要在replace()之上translate()?检查translate vs replace
replace()
Python 2.7版
myString.maketrans('X','X\n')
列表没有
split
方法(如错误所述)。假设
myList
是一个字符串列表,并且您希望在每个字符串中用'X\n'
替换'X'
,则可以使用列表理解:Python 3.X
translate()
允许dict,因此,一次可以替换多个不同的字符。为什么要在
replace()
之上translate()
?检查translate vs replacePython 2.7版
相关问题 更多 >
编程相关推荐