1

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 ?

Isoka05m
  • 33
  • 6

6 Answers6

2

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.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
1

Try this:

import re
listB = [re.sub('\d+', '', x).strip() for x in listA]
print(listB)

Output:

['Paris', 'Amsterdam', 'New York City', 'L.A']
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

This seems to work for me

listB=[]
for i in listA:
    listB.append(listA[0][:len(element)])
print(listB)
maria_g
  • 130
  • 1
  • 6
0

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 one
  • r"\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])
  • For more information about regex use this documentation page
Deerenaros
  • 30
  • 7
0

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])
DavideBrex
  • 2,374
  • 1
  • 10
  • 23
0

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.

mrkhrova
  • 86
  • 5