基本形式:print('hello world!')--->hello world
如果想在其中使用'而不被判定为结束或者开始的'需要加/,即 print ('hello/'world!')--->hello'world!
如果想输出变量的值则需要引入{}和format:
age=20
name='charles'#双引号也可以,如果是多行的字符串则使用三个单/双引号
#即'''........
#......
#.........'''
print ('My age is {0} and my name is {1}'.format(age, name))#注意是句号不是逗号
--->My age is 20 and my name is charles
如果想少写点可以写成print ('My age is {} and my name is {}'.format(age, name))与上面输出结果等价,但不推荐这样,不容易读而且容易出错。也可以在print中赋值print ('My age is {0} and my name is {1}'.format(age=20, name='charles'))
如果要输出浮点数,需要用如下格式 print('{0:.3f}'.format(1.0/3))--->0.333
有一些小操作比如 print('{0:_^11}'.format('hello'))--->___hello___ 在11个下划线中央插入了format中的字符
关于 end() 函数。它可以规定print的输出以什么结尾。比如python3的print结尾自带换行符\n,如果你不想换行就可以让结尾为空:
print('a', end='')
print('b', end='')
--->ab
#不想换行还有一种方法:
#"This is the first sentence. \
#This is the second sentence."
#--->"This is the first sentence. This is the second sentence."
当然也可以用别的结尾,比如:
print('a', end=' ')
print('b', end=' ')
print('c')
--->a b c
有时候需要看代码调试的话,我们不想让print中的转移符号产生作用,可以用raw print,这样可以完完全全打印出原汁原味的语句,如:
print(r"oooo \noo")#r或者R大小写都可以
--->ooo\noo
仅需打印某变量时可以直接:
i=1
s='wao'
print(i)
print(s)
--->1
--->wao
当然也可以直接在句子末尾大隐变量:
i=1
print ('i want', i)
--->i want 1