0

I did some workarounds but none of them worked so here I am with a question on how can we split a value from a list based on a keyword and update in the same list

    here is my code,
    result_list = ['48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS: 12FAIL: 1SKIP: 1\n2:25:36']

what I want to remove '\n' and write something like this,

result_list = ['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', .....]

iltech
  • 183
  • 1
  • 2
  • 11
  • 2
    You can use [`split()` to split a string to a list](https://stackoverflow.com/questions/743806/how-do-i-split-a-string-into-a-list-of-words): `result_list = result_list[0].split('\n')` – JNevill Oct 25 '22 at 13:10
  • The input value for result_list is a Python list comprised of one element which is a string. What would the output look like if the input list had more than one element? – DarkKnight Oct 25 '22 at 13:47

4 Answers4

1

You need to split each of the string by \n which results in a list that you need to flatten. You can use list-comprehension:

>>> [x for item in result_list for x in item.split('\n') ]
# output:
['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', 'Radar', 'completed 2022-10-25T10:43:01', 'PASS: 12FAIL: 1SKIP: 1', '2:25:36']
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

this will split each element of your list at \n and update in same list

result_list = [item for i in result_list for item in i.split('\n') ]

0

Solution using regex (re):

import re    
result_list = re.split('\n', result_list[0])

#output: 
['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', 'Radar', 'completed 2022-10-25T10:43:01', 'PASS: 12FAIL: 1SKIP: 1', '2:25:36']
sqhoward
  • 1
  • 1
0

The split() method of the str object does this:

Return a list of the words in the string, using sep as the delimiter string.

>>> '1,2,3'.split(',')
['1', '2', '3']

so here we have the answer as follows:

string_object = "48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS: 12FAIL: 1SKIP: 1\n2:25:36"

result_list = string_object.split(sep='\n')
Sadegh Pouriyan
  • 157
  • 1
  • 10