Python:从标准格式的字符串中提取浮点数

问题描述 投票:0回答:2

我想使用命令行参数argv[2],该参数将始终为split_pct=x的形式,其中x是指定的浮点数。为了澄清,下面是一些有效的示例:split_pct=90.0split_pct=55.23。对于给定的输入,如何提取该浮点数?

正在运行Python 3.7

python command-line floating-point argv
2个回答
0
投票

已解决-因为字符串是标准格式,所以我们只能获取split_pct=之后的值。 split_pct=是10个字符,因此

x = float(sys.argv[2][10:]

作品。


0
投票

您想研究类型转换:

x = 1.0
y = 2*x # 2.0
z = 2/x # 2.0

x = str(1.0)
y = 2*x # TypeError: unsupported operand type(s) for /: 'int' and 'str'
z = 2/x # TypeError: unsupported operand type(s) for /: 'int' and 'str'

w = float(x) # Cast to float
y = 2*w # 2.0
z = 2/w # 2.0

可以在here中找到更多信息。

要从命令行使用参数:

import sys
split_pct = sys.argv[2]

如果您的命令是这样,则可以使用:

python3 script.py first_var 90.0

由于脚本名称计为sys.argv[0],请参阅here了解更多详细信息:

© www.soinside.com 2019 - 2024. All rights reserved.