英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论