简体   繁体   English

在python列表中的字符串中用换行符替换字符

[英]Replacing a character with a new line in a string in a list in python

I have one long string of numbers in a list. 我列表中有一长串数字。 The numbers are separated with the character '\\r'. 数字用字符“ \\ r”分隔。

Looks something like this: 看起来像这样:

['5214661\\r3392815\\r4498905\\r309361\\r5214080\\r3020583\\r3089870\\r802553\\r4254266\\r1395033']

I'm trying to simply replace the character with a line break so that each number gets its own line, as such: 我试图简单地用换行符替换字符,以便每个数字都有自己的行,如下所示:

'5214661'
'3392815'
'4498905'
'309361'
'5214080'
... etc.
my_string_list = ['5214661\r3392815\r4498905\r309361\r5214080\r3020583\r3089870\r802553\r4254266\r1395033']

for my_number in my_string_list[0].split('\r'):
    print my_number

#Output
5214661
3392815
...
1395033

Is this what you need? 这是您需要的吗?

You can also do this in single line as: 您也可以单行执行以下操作:

print my_string_list[0].replace("\r", "\n")

You could also use splitlines() 您也可以使用splitlines()

print("\n".join(k[0].splitlines()))

In the REPL 在REPL中

>>> k = ['5214661\r3392815\r4498905\r309361\r5214080\r3020583\r3089870\r802553\r4254266\r1395033']
>>> print("\n".join(k[0].splitlines()))
5214661
3392815
4498905
309361
5214080
3020583
3089870
802553
4254266
1395033

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM