从列表中的字符串开头删除数字字符。

huangapple go评论79阅读模式
英文:

Strip number characters from start of string in list

问题

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

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

mylist = ['John',
 'James',
 'Mark',
 'Mary',
 'Helen',
 'David']
英文:
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']

答案1

得分: 1

如果你真的想使用strip,你可以尝试:

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

或者如@Michael Butscher提到的,要提取名称部分,你可以简单地使用split方法将字符串按空格分成两部分['1.', 'John'],然后提取最后一部分:

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

结果:
['John', 'James', 'Mark', 'Mary', 'Helen', 'David']

英文:

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']

答案2

得分: 0

你可以使用正则表达式。

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)

# 输出: ['John', 'James', 'Mark', 'Mary', 'Helen', 'David']
英文:

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']

答案3

得分: 0

以下是翻译好的代码部分:

尝试这个

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))
英文:

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))

huangapple
  • 本文由 发表于 2023年2月10日 12:19:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定