Python由放弃到入门,基础篇一( 最常用的三种数据类型)
程序员文章站
2022-06-06 09:22:20
...
最常用的数据类型有三种——字符串(str)、整数(int)和浮点数(float)
字符串(str)
#!/usr/bin/python3
slogan = '命运!不配做我的对手!'
attack = "308"
gold = "48g"
blood = '''+101'''
achieve = "First Blood!"
print(slogan)
print(attack)
print(gold)
print(blood)
print(achieve)
print('''三顾茅庐,
官渡之战,
赤壁之战,
败走麦城,
三家归晋。
''')
>>>>>>>>>>>>>>>>>>>>>>>>
命运!不配做我的对手!
308
48g
+101
First Blood!
三顾茅庐,
官渡之战,
赤壁之战,
败走麦城,
三家归晋。
PS:字符串类型必须有引号的辅助
整数(int)
#!/usr/bin/python3
print(666)
print(499*561+10620-365)
>>>>>>>>>>>>>>>>>>>>>>>>
666
290194
浮点数(float)
#例子
1.0
3.14159
-0.33
数据拼接
#!/usr/bin/python3
hero1 = '曹操'
hero2 = '刘备'
action = '秒掉'
gain = '获得'
achieve = 'First Blood'
print(hero1+action+hero2+gain+achieve)
print(hero2+action+hero1+gain+achieve)
PS:用“+”号将数据进行拼接
>>>>>>>>>>>>>>>>>>>>>>>>
曹操秒掉刘备获得First Blood
刘备秒掉曹操获得First Blood
type()函数
#!/usr/bin/python3
hero = '亚瑟'
enemy = '敌方'
action = '秒杀'
gain = '获得'
number = 5
achieve = 'Penta Kill'
print(type(hero))
print(type(enemy))
print(type(action))
print(type(gain))
print(type(number))
print(type(achieve))
>>>>>>>>>>>>>>>>>>>>>>>>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'str'>
数据转换
str()函数能将数据转换成其字符串类型
#!/usr/bin/python3
number = 500
print(type(number))
print(type('500'))
print(type(str(number)))
>>>>>>>>>>>>>>>>>>>>>>>>
<class 'int'>
<class 'str'>
<class 'str'>
PS:整数类型转换为字符串类型
int()函数能将数据转换成其字符串类型
#!/usr/bin/python3
bug = '666'
print(type(bug))
print(type(int(bug)))
>>>>>>>>>>>>>>>>>>>>>>>>
<class 'str'>
<class 'int'>
PS:字符串类型转换为整数类型
float()函数能将数据转换成其字符串类型
#!/usr/bin/python3
height = 183.5
weight = 79
age = '30'
print(type(height))
print(type(weight))
print(type(age))
print(float(height))
print(float(weight))
print(float(age))
print(type(float(height)))
print(type(float(weight)))
print(type(float(age)))
PS:字符串及整数类型转换为浮点型