目录
1、print:
print函数原型:print(self,*args,sep=' ',end='\n',file=None)
(1)self:
(2)*args:arguments:多参数
>>> print(1)
1
>>> print(1,2,3)
1 2 3
(3)sep:多个数据之间的间隔,默认是一个空格
>>> print(1,2,3,sep = '!')
1!2!3
(4)end:结尾默认换行(\n)
>>> print(1,2,3,sep = '#' , end = '哈哈')
1#2#3哈哈>>> print(1,2,3,sep = '#' , end = '哈哈\n')
1#2#3哈哈
>>>
2、占位符
>>> name='旺财'
>>> age=18
>>> print(name,age)
旺财 18
>>> print('abc'+'ABC')
abcABC
>>> print('你叫'+'旺财')
你叫旺财
>>> print('你叫'+name+'今年'+age+'岁') #拼接只能是两个字符串
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print("你叫%s,你是%d岁"%(name,age))
你叫旺财,你是18岁
常见的占位符:
%s:表示字符串数据
%d:表示整数数据
%f:表示浮点型数据
3、input
input(): 获取用户的数据,输入的数据是一个字符串
>>> a = input()
我是你大爷!
>>> a
'我是你大爷!'
>>> b = input()
10 #输入10
>>> b
'10' #字符串
>>> c = input('请输入你的年龄:')
请输入你的年龄:12
>>> c
'12'
4、eval
eval函数:解析字符串中的数字、整数、小数、其它进制的整数
>>> eval('3')
3
>>> eval('3.14')
3.14
>>> eval('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
>>> eval('"abc"')
'abc'
>>> eval('0b1001')
9
>>> eval('0o1001')
513
>>> eval('0x1001')
4097
用户多数据输入要依靠eval:
>>> a,b,c = eval(input("请输入三个数字:"))
请输入三个数字:10,20,30
>>> a,b,c(10, 20, 30)
>>> a+b+c60
>>> d,e,f=eval(input('请输入三个名字:'))
请输入三个名字:'小红','小明','小军'
>>> d+e+f
'小红小明小军'
5、int
int函数:将整数字符串或浮点数转化为整数
>>> int('3') #整数字符串
3
>>> int('3.14')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.14'
>>> int(3.14) #浮点数
3
>>> int(3.9)
3
也可以指定进制:
>>> int('1001',2) #最低二进制9
>>> int('1001',36) #最高三十六进制
46657
6、float
float函数:将小数字符串或整数转化为浮点数
>>> float('3.14')
3.14
>>> float('3')
3.0
>>> float(3)
3.0
>>> float('3.1a4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '3.1a4'
7、str
str函数:将对象转换成字符串类型
>>> a=10
>>> str(a)
'10'
>>> name='旺财'
>>> age=10
>>> print(name+age) #只能字符串和字符串相拼接
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print(name+str(age)) #将对象转化成字符串类型
旺财10
>>> print(name+'age')
旺财age