[英]Best way to remove spaces between digits and sum python <class 'str'>?
I am a learner and currently working on a task now and almost finished, but I got stuck with how finish up.我是一名学习者,目前正在处理一项任务,几乎完成了,但我对如何完成感到困惑。 I have a < class 'str'> that looks like:
我有一个 < class 'str'> 看起来像:
I need to remove the spaces in-between the 2-digit numbers, so I can easily sum the whole numbers.我需要删除 2 位数字之间的空格,这样我就可以轻松地将整数相加。 Below is the exact string:
下面是确切的字符串:
9 7 9 7 9 0 9 0 8 8 8 7 8 7 8 0
7 9 7 9 7 8 7 6 7 6 7 2 7 2 6 6 6 6 6 5 6 5 6 4 6
1 6 1 5 9 5 8 5 7 5 7 5 4 5 1 4 9 4 7 4 0 3 8 3 7
3 6 3 6 3 2 2 5 2 4 2 2 2 1 1 9 1 8 1 8 1 4 1 2
1 2 9 7 3 2
I have checked similar answers here with Regex, and every solution I tried seems to just either remove all the spaces(leaving one long string of digits) or separate them into single digits.我在这里用正则表达式检查了类似的答案,我尝试的每个解决方案似乎只是删除所有空格(留下一长串数字)或将它们分成单个数字。
What is the best way to solve this problem?解决这个问题的最佳方法是什么?
You can use a regex to look for a digit '\d'
that is optionally followed by a single space and then another digit '(?: \d)?'
您可以使用正则表达式来查找一个数字
'\d'
,可以选择后跟一个空格,然后是另一个数字'(?: \d)?'
. . Then in a list comprehension remove the middle whitespace if there is one
然后在列表理解中删除中间空格(如果有的话)
>>> [i.replace(' ', '') for i in re.findall(r'(\d(?: \d)?)', s)]
['97', '97', '90', '90', '88', '87', '87', '80', '79', '79', '78', '76', '76', '72', '72', '66', '66', '65', '65', '64', '6', '1', '61', '59', '58', '57', '57', '54', '51', '49', '47', '40', '38', '37', '36', '36', '32', '25', '24', '22', '21', '19', '18', '18', '14', '12', '12', '9', '7', '3', '2']
To convert these into int
types将这些转换为
int
类型
>>> [int(i.replace(' ', '')) for i in re.findall(r'(\d(?: \d)?)', s)]
[97, 97, 90, 90, 88, 87, 87, 80, 79, 79, 78, 76, 76, 72, 72, 66, 66, 65, 65, 64, 6, 1, 61, 59, 58, 57, 57, 54, 51, 49, 47, 40, 38, 37, 36, 36, 32, 25, 24, 22, 21, 19, 18, 18, 14, 12, 12, 9, 7, 3, 2]
and to sum them并总结它们
>>> sum(int(i.replace(' ', '')) for i in re.findall(r'(\d(?: \d)?)', s))
2499
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.