Strip number characters from start of string in list

Question:

my_list = ['1. John',
 '2. James',
 '3. Mark',
 '4. Mary',
 '5. Helen',
 '6. David']

I would like to remove the number that is a string, the "." and the white space before the name.

for i in my_list:
  i.lstrip(". ")

I was hoping the output would be a list as such:

mylist = ['John', 
  'James',
  'Mark', 
  'Mary',
  'Helen',
  'David']
Asked By: laclanthony

||

Answers:

If you really want to use strip, you can try:

my_list = ['1. John', '2. James', '3. Mark', '4. Mary', '5. Helen', '6. David']
name_list = [item.lstrip('1234567890. ') for item in my_list]

Or as @Michael Butscher mentioned, to retrieve the name part you can simply use split to split the string by space into two part ['1.', 'John'] and retrieve the last part:

name_list= [item.split(' ')[-1] for item in my_list]

Result:
['John', 'James', 'Mark', 'Mary', 'Helen', 'David']

Answered By: dinhit

You could use regex.

import re

regex = re.compile(r'(d+).s')
my_list = ['1. John', '2. James', '3. Mark', '4. Mary', '5. Helen', '6. David']
new_list = [re.sub(regex, '', item) for item in my_list]
print(new_list)

# Output: ['John', 'James', 'Mark', 'Mary', 'Helen', 'David']
Answered By: State

try this:

def strip_numbers(my_list):
    result = []
    for i in my_list:
        x = i.split(". ")
        result.append(x[1])
    return result
print(strip_numbers(my_list))
Answered By: Taner_smail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.