len()大家好,我是胡亥大魔王。今天介绍python中的四个常用函数len()、str()、int()和float()
len()函数传递一个字符串或者包含字符串的变量,然后返回一个整型值,即字符串中字符的个数。
len('hello python.')
输出:13
len('')
输出:0
str()有时我们需要将整数和字符串连接起来使用,但是如下写法是不可行的:
print('I am ' + 18 + ' years old.')
报错:
Traceback (most recent call last): File "", line 1, in print('I am ' + 18 + ' years old.') TypeError: can only concatenate str (not "int") to str
这是由于整数和字符串是不能直接连接的,需要把整数转换成字符串'18'才可以
print('I am ' + str(18) + ' years old.')
输出:
int()和float()的用法和str()类似
- int()是将输入值转换成整型
- 如果输入值是浮点型,则取整数
- 对于字符串:如果字符串是数字,则直接转换;如果字符串不是数字,则报错
- float()是将输入值转换成浮点型,如果无法转换,则报错
不会四舍五入,而是取整
print(int(5.3)) print(int(5.5)) print(int(5.8))
输出:
字符串无法转换
print(int('twelve'))
# 或者
print(float('twelve'))
报错!无法转换



