python int string_Python中,int(x)的x可以为字符串(比如"6.9")吗?

int() 函数是可以接受一个字符串参数的。但"6.9"不能转换为 int 类型,应该用 float() 函数将整数和字符串转换成浮点数。在这里如果用 int() 函数转换将会报错,但可以用 int() 函数转换 '6',如:

int('6')

# 6

int('6.9')

Traceback (most recent call last):

File "", line 1, in

ValueError: invalid literal for int() with base 10: '6.9'

float('6.9')

# 6.9

classfloat([x])

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign ::= "+" | "-"

infinity ::= "Infinity" | "inf"

nan ::= "nan"

numeric_value ::= floatnumber | infinity | nan

numeric_string ::= [sign] numeric_value

......

classint([x])classint(x,base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines int(x) returns x.__int__(). If x defines x.__trunc__(). For floating point numbers, this truncates towards zero.

其实以上我都是直接摘录自 Python 官方文档的,像这种简单的也可以试试再同时阅读 Python 官方文档,只要打开命令提示符就可以马上知道答案了,但要了解就必须阅读文档或书籍了。

https://docs.python.org/3.7/library/functions.html#int​docs.python.orghttps://docs.python.org/3.7/library/functions.html#float​docs.python.orghttps://docs.python.org/3.7/reference/lexical_analysis.html#floating​docs.python.org

如果你上网不太方便,还可以使用离线文档。如,离线 API 文档浏览器 Zeal。Zeal 是软件开发人员的离线文档浏览器。支持 Windows 和 Linux 平台。Windows 平台包含安装版和便携版。离线 API 文档浏览器 Zeal

Zeal 官方地址:https://zealdocs.org/​zealdocs.org

我曾经在简书中记录过的关于使用 Zeal 的笔记:离线 API 文档浏览器 Zeal​www.jianshu.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值