繁体   English   中英

从字符串中删除小数但在 Python 中保留整数

[英]Remove Decimal Numbers From String but Retain Whole Numbers in Python

我有许多包含文本、特殊字符、十进制数和整数的字符串。 这里有些例子:

Run Ho 1132  0.0,-0.5

Run Af 29  0.0

理论上,整数可以是任意大小,但十进制数在小数点两侧最多有 3 位数字。

我想删除十进制数字以及任何逗号和 - 符号,但保留所有整数。

所以在上面的例子中,所需的输出是:

Run Ho 1132

Run Af 29

这可能吗?

您可以通过splitslicingjoin 来实现

strings = ("Run Ho 1132  0.0,-0.5" ,"Run Af 29  0.0")
print([' '.join(string.split()[:3]) for string in strings])
# Outputs ['Run Ho 1132', 'Run Af 29']

如果您输入的格式不固定,您可以考虑使用 Regex:

import re
# Reads "0/1 whitespace followed by (1+ letters or 1+ numbers) followed by 1 whitespace"
# This will match a word and only integers, since a dot is not whitespace
pattern = re.compile(r'\s?(\w+|\d+)\s')

strings = ("Run Ho 1132  0.0,-0.5" ,"Run Af 29  0.0", "Run Pm 3.14  45")
replaced = []
for string in strings:
    match = pattern.findall(string)
    if match is None:
        continue
    replaced.append(' '.join(match))
    
print(replaced)
# Outputs ['Run Ho 1132', 'Run Af 29', 'Run Pm 45']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM