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

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

Strip number characters from start of string in list

问题

  1. my_list = ['1. John',
  2. '2. James',
  3. '3. Mark',
  4. '4. Mary',
  5. '5. Helen',
  6. '6. David']
  7. for i in my_list:
  8. i = i.lstrip(". ")
  9. mylist = ['John',
  10. 'James',
  11. 'Mark',
  12. 'Mary',
  13. 'Helen',
  14. 'David']
英文:
  1. my_list = ['1. John',
  2. '2. James',
  3. '3. Mark',
  4. '4. Mary',
  5. '5. Helen',
  6. '6. David']

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

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

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

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

答案1

得分: 1

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

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

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

  1. 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:

  1. my_list = ['1. John', '2. James', '3. Mark', '4. Mary', '5. Helen', '6. David']
  2. 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:

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

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

答案2

得分: 0

你可以使用正则表达式。

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

You could use regex.

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

答案3

得分: 0

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

  1. 尝试这个
  2. def strip_numbers(my_list):
  3. result = []
  4. for i in my_list:
  5. x = i.split(". ")
  6. result.append(x[1])
  7. return result
  8. print(strip_numbers(my_list))
英文:

try this:

  1. def strip_numbers(my_list):
  2. result = []
  3. for i in my_list:
  4. x = i.split(". ")
  5. result.append(x[1])
  6. return result
  7. 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:

确定