Home > Software engineering >  Split these strings while inside a list
Split these strings while inside a list

Time:12-28

So I have this list:

[
  '92\nMetaverse Psychedelics Anonymous Pass\n44.6\n 1185.27%\n---\n0.08\n6.4K\n9.5K', 
  '100\nCryptoDickbutts\n41.42\n 896.92%\n 105.73%\n0.75\n1.5K\n5.2K', 
  '20\nArt Blocks Factory\n355.01\n 798.96%\n 122.79%\n---\n20.4K\n79.3K'
]

And I need help finding a good way to split the list items at every "\n". Split wont work because I'm assuming that it doesn't register the \n as part of the string...

CodePudding user response:

I'm not 100% sure what the result should be, but this is an idea:

>>> t = [
...   '92\nMetaverse Psychedelics Anonymous Pass\n44.6\n 1185.27%\n---\n0.08\n6.4K\n9.5K',
...   '100\nCryptoDickbutts\n41.42\n 896.92%\n 105.73%\n0.75\n1.5K\n5.2K',
...   '20\nArt Blocks Factory\n355.01\n 798.96%\n 122.79%\n---\n20.4K\n79.3K'
... ]

>>> for i in t:
...     print(i.splitlines())
...
['92', 'Metaverse Psychedelics Anonymous Pass', '44.6', ' 1185.27%', '---', '0.08', '6.4K', '9.5K']
['100', 'CryptoDickbutts', '41.42', ' 896.92%', ' 105.73%', '0.75', '1.5K', '5.2K']
['20', 'Art Blocks Factory', '355.01', ' 798.96%', ' 122.79%', '---', '20.4K', '79.3K']

>>> p = [x for i in t for x in i.splitlines()]
>>>
>>> p
['92', 'Metaverse Psychedelics Anonymous Pass', '44.6', ' 1185.27%', '---', '0.08', '6.4K', '9.5K', '100', 'CryptoDickbutts', '41.42', ' 896.92%', ' 105.73%', '0.75', '1.5K', '5.2K', '20', 'Art Blocks Factory', '355.01', ' 798.96%', ' 122.79%', '---', '20.4K', '79.3K']

CodePudding user response:

You could do this

my_list = [
  '92\nMetaverse Psychedelics Anonymous Pass\n44.6\n 1185.27%\n---\n0.08\n6.4K\n9.5K', 
  '100\nCryptoDickbutts\n41.42\n 896.92%\n 105.73%\n0.75\n1.5K\n5.2K', 
  '20\nArt Blocks Factory\n355.01\n 798.96%\n 122.79%\n---\n20.4K\n79.3K'
]

new_list = []

for string in my_list:
    # .extend is like append but it appends all items of the list which in this case is the string split by "\n"
    new_list.extend(string.split("\n")) 

print(new_list)

It loops through the list of strings and splits them by the newline.

CodePudding user response:

You can use this code

my_list = [
  '92\nMetaverse Psychedelics Anonymous Pass\n44.6\n 1185.27%\n---\n0.08\n6.4K\n9.5K', 
  '100\nCryptoDickbutts\n41.42\n 896.92%\n 105.73%\n0.75\n1.5K\n5.2K', 
  '20\nArt Blocks Factory\n355.01\n 798.96%\n 122.79%\n---\n20.4K\n79.3K'
]

new_list = []

for item in my_list:
    new = item.split('\n')
    new_list.append(' '.join(new))


then I guess you will have what you need

  • Related