How to map all numbers in a string to a list in Python?
本问题已经有最佳答案,请猛点这里访问。
比如说我有一根绳子
1 | "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)" |
我希望能够动态地将这些数字提取到一个列表中:
换句话说,有没有方法提取由任何分隔符分隔的连续数字簇?
当然,使用正则表达式:
1 2 3 4 | >>> s ="There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)" >>> import re >>> list(map(int, re.findall(r'[0-9]+', s))) [34, 0, 4, 5] |
您也可以在不使用正则表达式的情况下执行此操作,尽管这需要做更多的工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> s ="There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)" >>> #replace nondigit characters with a space ... s ="".join(x if x.isdigit() else"" for x in s) >>> print s 34 0 4 5 >>> #get the separate digit strings ... digitStrings = s.split() >>> print digitStrings ['34', '0', '4', '5'] >>> #convert strings to numbers ... numbers = map(int, digitStrings) >>> print numbers [34, 0, 4, 5] |
号