Sam*_*nks 17 python type-conversion python-3.x
所以在我的代码中我通常这样做将字符串转换为int,但我想知道是否有一种不那么笨拙的方式,因为它感觉有点长.
my_input = int(my_input)
Run Code Online (Sandbox Code Playgroud)
也许这就是它必须如何,但如果你有任何想法,请提前感谢.
Gon*_*alo 25
首先,该int函数将变量的值转换为字符串.鉴于您正在尝试将字符串转换为int,我建议您使用该int函数(https://docs.python.org/3/library/functions.html#int).
你的python代码看起来像:
my_input = int(my_input)
Run Code Online (Sandbox Code Playgroud)
这个3个字母的功能可以在短时间内满足您的需求.实际上在Java等其他语言中,语法几乎是其两倍.
Java示例
my_input = int(my_input)
Run Code Online (Sandbox Code Playgroud)
也许您希望得到类似的东西my_number = my_input.to_int。但目前还无法在本地实现这一点。有趣的是,如果你想从类似浮点的字符串中提取整数部分,你必须float先转换为 ,然后再转换为int。否则你会得到ValueError: invalid literal for int()。
稳健的方式:
my_input = int(float(my_input))
Run Code Online (Sandbox Code Playgroud)
例如:
>>> nb = "88.8"
>>> int(nb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '88.8'
>>> int(float(nb))
88
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77890 次 |
| 最近记录: |