简体   繁体   中英

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'.

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()

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

In the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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