当前位置:首页 > 编程技术 > 正文

python如何去小数点

python如何去小数点

在Python中,如果你想要去除数字中的小数点,可以使用字符串的`replace( `方法或者使用正则表达式。以下是一些示例代码: 使用 `replace( ` 方法`...

在Python中,如果你想要去除数字中的小数点,可以使用字符串的`replace()`方法或者使用正则表达式。以下是一些示例代码:

使用 `replace()` 方法

```python

number = 123.456

number_str = str(number)

number_without_decimal = number_str.replace('.', '')

print(number_without_decimal) 输出: 123456

```

使用正则表达式

```python

import re

number = 123.456

number_str = str(number)

number_without_decimal = re.sub(r'.d+', '', number_str)

print(number_without_decimal) 输出: 123

```

第一个方法会将所有的小数点及其后面的数字替换为空字符串,第二个方法只会移除小数点,而保留小数点后面的数字。根据你的具体需求,你可以选择合适的方法。

最新文章