Python 如何从字符串列表中删除连字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40954324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:15:22 来源:igfitidea点击:
How to remove hyphens from a list of strings
提问by Hodgson Xue
['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']
How can I remove all the hyphens between the numbers?
如何删除数字之间的所有连字符?
回答by SamOh
You can just iterate through with a for loop and replace each instance of a hyphen with a blank.
您可以使用 for 循环进行迭代,并将连字符的每个实例替换为空白。
hyphenlist = ['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']
newlist = []
for x in hyphenlist:
newlist.append(x.replace('-', ''))
This code should give you a newlist without the hyphens.
这段代码应该给你一个没有连字符的新列表。
回答by LMc
Or as a list comprehension:
或者作为列表理解:
>>>l=['0-0-0', '1-10-20', '3-10-15', '2-30-20', '1-0-5', '1-10-6', '3-10-30', '3-10-4']
>>>[i.replace('-','') for i in l]
['000', '11020', '31015', '23020', '105', '1106', '31030', '3104']