简体   繁体   English

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

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

I have a number of strings that contain a mixture of text, special characters, decimal numbers and whole numbers.我有许多包含文本、特殊字符、十进制数和整数的字符串。 Here are some examples:这里有些例子:

Run Ho 1132  0.0,-0.5

Run Af 29  0.0

The whole numbers can in theory be any size but the decimal numbers will have a maximum of 3 digits either side of the decimal point.理论上,整数可以是任意大小,但十进制数在小数点两侧最多有 3 位数字。

I want to remove the decimal numbers along with any commas and - symbols but retain all whole numbers.我想删除十进制数字以及任何逗号和 - 符号,但保留所有整数。

So in the above examples the desired output is:所以在上面的例子中,所需的输出是:

Run Ho 1132

Run Af 29

Is this possible?这可能吗?

You can do it by splitting , slicing and joining :您可以通过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']

If your input's format is not fixed, you may consider Regex:如果您输入的格式不固定,您可以考虑使用 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