Home > Net >  List split and join
List split and join

Time:02-07

Below is my list

MY_TXT= [
    'User enters validusername "MAXI" And password "768"', 
    'User enters phonenumber "76567898" And ZIPcode "97656"', 
    'User Verifys Country "ENGLAND" And City "LONDON"  And  street "Brick Lane And avenue  "2A"',
    'User clicks ok']

I want split the list from 'And' and join with base name , my list to be looks like this:

New_list= [
    'User enters validusername "MAXI"',
    'User enter password "768"',    
    'User enters phonenumber "76567898"',
    'User enters ZIPcode "97656"', 
    'User Verifys Country "ENGLAND",
    'User Verifys City "LONDON"',
    'User Verifys street "Brick Lane"',
    'User Verifys  avenue  "2A"',
    'User clicks ok']

CodePudding user response:

Create an empty list new_list. Using a for loop, split each string using MY_TXT[i].split("And"). Then new_list = new_list results

CodePudding user response:

If you do a nested list comprehension you can get what you're after:

In [6]: ['User verifys ' j if 'User'!=j[:4] else j for i in MY_TXT for j in i.split('And ')]
Out[6]: 
['User enters validusername "MAXI" ',
 'User verifys password "768"',
 'User enters phonenumber "76567898" ',
 'User verifys ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User verifys City "LONDON" ',
 'User verifys street "Brick Lane ',
 'User verifys avenue "2A"',
 'User clicks ok']

------- EDIT --------

I see that it's not always 'verify'. In this case you'll need to track the variable which is the one you want to use at the start of the string ('verifys', 'enter', etc)

In [17]: myList = []

In [18]: for i in MY_TXT:
    ...:     for j in i.split('And '):
    ...:         if 'User' in j:
    ...:             entryStr = j.split()[1] #extract the action of the user - enters, verifys, etc
    ...:             myList.append(j)
    ...:         else:
    ...:             myList.append('User {:s} {:s}'.format(entryStr,j))
    ...: 
In [19]: myList
Out[19]: 
['User enters validusername "MAXI" ',
 'User enters password "768"',
 'User enters phonenumber "76567898" ',
 'User enters ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User Verifys City "LONDON" ',
 'User Verifys street "Brick Lane ',
 'User Verifys avenue "2A"',
 'User clicks ok']
  •  Tags:  
  • Related