马士兵教育 Python 入门基础:1.python 入门(一)
马士兵教育 Python 入门基础:1.python 入门(二)
# 数据类型转换

name="张三" | |
age=20 | |
print (type (name),type (age)) | |
<class'str'> <class 'int'> | |
print (' 我叫 '+name+' 今年 '+age+"岁") | |
TypeError: can only concatenate str (not "int") to str# 需要类型转换才能不会报错 | |
print (' 我叫 '+name+' 今年 '+str (age)+"岁") | |
我叫张三今年 20 岁 |
print ('---------------- 将其他类型转换为 str 类型 ---------') | |
a=10 | |
b=198.8 | |
c=False | |
print (type (a),type (b),type (c)) | |
print (str (a),str (b),str (c),type (str (a)),type (str (b)),type (str (c))) | |
---------------- 将其他类型转换为 str 类型 --------- | |
<class 'int'> <class 'float'> <class 'bool'> | |
10 198.8 False <class'str'> <class'str'> <class'str'> |
print ('----------------- 将其他类型转换为 int 类型 ---------') | |
sl='128' | |
f1=98.7 | |
s2='76.77' | |
ff=True | |
s3="hello" | |
print (type (s1),type (f1),type (s2),type (ff),type (s3)) | |
print (int (s1),type (int (s1)))# 将 str 转成 int 型,字符串为数字串 | |
print (int (f1),type (int (f1)))# 直截取整数部分,舍弃小数点之后 | |
#print (int (s2),type (int (s2)))# 字符串为小数串报错 | |
print (int (ff),type (int (ff))) | |
#print (int (s3),type (int (s3)))# 将字符串转换为 int 时,必须为整数串 | |
----------------- 将其他类型转换为 int 类型 --------- | |
<class'str'> <class 'float'> <class'str'> <class 'bool'> <class'str'> | |
128 <class 'int'> | |
98 <class 'int'> | |
1 <class 'int'> |
print ('-------------- 将其他类型转换为浮点数 -----------------') | |
s1='128.98' | |
s2='76' | |
ff=True | |
s3="hello" | |
i=98 | |
print (type (s1),type (f1),type (s2),type (ff),type (s3),type (i)) | |
print (float (s1),type (float (s1))) | |
print (float (s2),type (float (s2))) | |
print (float (ff),type (float (ff))) | |
#print (int (s3),type (float (s3)))# 字符串为非数字字符串报错 | |
print (float (i),type (float (i))) | |
-------------- 将其他类型转换为浮点数 ----------------- | |
<class'str'> <class 'float'> <class'str'> <class 'bool'> <class'str'> <class 'int'> | |
128.98 <class 'float'> | |
76.0 <class 'float'> | |
1.0 <class 'float'> | |
98.0 <class 'float'> |
# Python 中的注释

#coding:gbk 修改编码格式 | |
# 输入功能:单行注释 | |
print ('hello') | |
''' | |
嘿嘿, | |
我是 | |
多行注释 | |
''' |
# 第二章总结
