Reputation: 33
I have a list in which I add elements like this:
listA.append('{:<30s} {:>10s}'.format(element, str(code)))
so listA looks like this:
Paris 75
Amsterdam 120
New York City 444
L.A 845
I would like, now from this listA, to add elements to a "listB" list, without the code. I would like to do this:
for i in listA:
listB.append(i - str(code)) #that's what i want to do. The code is not good
and I want the listB to look like this:
Paris
Amsterdam
New York City
L.A
and only using listA and without having access to 'element' and 'code'
Can someone can help me ?
Upvotes: 1
Views: 285
Reputation: 1
Easiest way without any new libraries.
You can create a variable with 40 spaces(because of 40 spaces in the format clause). eg: space_var = " "
Then use the following code to extract element from listA
:
listB=[]
for i in listA:
listB.append(listA[0].rsplit(space_var,1)[0])
Upvotes: 0
Reputation: 30
How about to use re.sub
? And instead of using for in
it would be better to map
functional style or [for in]
list comprehension:
import re
listB = list(map(lambda x: re.sub(r"\s+\d+", "", x), listA))
or, even better
import re
listB = [re.sub(r"\s+\d+", "", x) for x in listA]
A little about regex:
re.sub
- is a function what searches an removes all occurrences of first argument to second in third oner"\s+\d+"
- is a 'raw' string literal with regex inside\s+
- one or more whitespaces (\t\n\r
etc)\d+
- one or more digits (\d
is an allias for [0-9]
)Upvotes: 0
Reputation: 94
You can try the following:
listB = [element.rsplit(' ', maxsplit=1)[0].rstrip() for element in listA]
rsplit(' ', maxsplit=1)
means you will split the element of listA once at first space from the right side. Additional rstrip()
will get rid of the other spaces from the right side.
Upvotes: 0
Reputation: 130
This seems to work for me
listB=[]
for i in listA:
listB.append(listA[0][:len(element)])
print(listB)
Upvotes: 0
Reputation: 9061
Try this:
import re
listB = [re.sub('\d+', '', x).strip() for x in listA]
print(listB)
Output:
['Paris', 'Amsterdam', 'New York City', 'L.A']
Upvotes: 1
Reputation: 4472
You can use regex for that
import re
for i in listA:
listB.append(re.sub(r"\W+\d+", "", i))
This will remove the code that is numbers and the spaces before it.
Upvotes: 2