欢迎关注微信公众号(医学生物信息学),医学生的生信笔记,记录学习过程。
浮点型转成整数型
# float类型转成int类型,只保留整数部分
print('float类型转成int类型:',int(3.14))
print('float类型转成int类型:',int(3.9))
print('float类型转成int类型:',int(-3.14))
print('float类型转成int类型:',int(-3.9))
整数型转成浮点型
# 将int转成float类型
print('将int转成float类型:',float(10))
字符串转成整数型
# 将str转成int类型
print(int('100')+int('200'))
有些字符串转整数型或浮点型报错
# 将字符串转成int或float时报错的情况
print(int('18a')) # ValueError: invalid literal for int() with base 10: '18a'
print(int('3.14')) # ValueError: invalid literal for int() with base 10: '3.14'
print(float('45a.987')) # ValueError: could not convert string to float: '45a.987'
十进制与其它进制之间的转换
print('十进制转成十六进制:',hex(26472))
print('十进制转成八进制:',oct(26472))
print('十进制转成二进制:',bin(26472))
隐式转换
整数型转换成浮点型:
x=10
y=3
z=x/y # 在执行除法运算的时候,将运算的结果赋值给z
print(z,type(z)) # 隐式转换,通过运算隐式的转了结果的类型
chr()
和ord()
函数
print(ord('杨')) #杨在unicode表中对应的整数值
print((chr(26472))) # 26472整数在unicode表中对应的字符是什么
eval()
函数
s='3.14+3'
print(s,type(s))
x=eval(s) # 使用eval函数去掉s这个字符串中左右的引号 ,执行加法运算
print(x,type(x))
# eval函数经常与input()函数一起使用,用来获取用户输入的数值
age=eval(input('请输入您的年龄:')) # 将字符串类型转成了int类型,相当于int(age)
print(age,type(age))
height=eval(input('请输入您的身高:'))
print(height,type(height))
hello='北京欢迎你'
print(hello)
print(eval('hello')) # 输出了"北京欢迎你"
print(eval('北京欢迎你')) # NameError: name '北京欢迎你' is not defined
参考资料
[1] https://www.bilibili.com/video/BV1wD4y1o7AS/?p=7&share_source=copy_web&vd_source=d40f0854606900163a564a59cfa3027c
[2] 零基础Python学习笔记 明日科技编著