简体   繁体   中英

how to i split this list into the same list without creating new list

how do I split this list

['charmander|4/16/2022 18:5:52|Good to see you!', 'charmander|4/16/2022 18:6:0|Good to see you!']

to

['charmander', '4/16/2022 18:5:52', 'Good to see you!' , 'charmander', '4/16/2022 18:5:52', 'Good to see you!']

by the way, this list is part of a txt file and has been split already by doing this

file = open('messages/' + username + '.txt', 'r')

data = file.read().strip()

results = data.split("\n")

You can do it like this using string.split("|")

l = ['charmander|4/16/2022 18:5:52|Good to see you!', 'charmander|4/16/2022 18:6:0|Good to see you!']
newList = []
for val in l:
    newList += (val.split("|"))

Output:
['charmander',
 '4/16/2022 18:5:52',
 'Good to see you!',
 'charmander',
 '4/16/2022 18:6:0',
 'Good to see you!']

Maybe you could try a list-comprehension :

with open(f'messages/{username}.txt', 'r') as file:
    data = file.read().strip()
results = [s.split('|') for s in data.split('\n')]
print(results)

Output:

['charmander', '4/16/2022 18:5:52', 'Good to see you!' , 'charmander', '4/16/2022 18:5:52', 'Good to see you!']

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