1. %?格式化
亲爱的×××你好,您的月租费用为××,余额为××
××的内容根据变量变化,因此需要一种简便的格式化字符串的方式。
>>>'hello, %s' % 'world' 'hello, world' >>>'hi, %s, you have %d.' % ('Thiago', 10000000) 'hi, Thiago, you have 10000000.'
%运算符是用来格式化字符串的。
在字符内部,
%s表示用字符串(string)替换,
%d表示用整数(digit?)替换,
%f表示用浮点数(float)替换,
%x表示用十六进制整数(hex)替换。
有几个%?占位符,后面就跟几个变量,或者值;顺序要对应好,用括号括起来;如果只有一个%?,括号可以省略。
如果不确定应该用什么,那么%s永远起作用。
字符串里面如果有%字符,应该加一个%来转义,既%%,这样才能吧百分号print出来。
2. .format格式化
age = 20 name = 'Thiago' print('{0} was {1} years old when he started learning Python.' .format(name, age)) print('Why is {0} playing with a python?' .format(name))
输出为:
Thiago was 20 years old when he started learning Python. Why is Thiago playing with a python?
数字只是可选项,你也可以写成:
print('{} was {} years old when he started learning Python' .format(name, age)) print('Why is {} playing with a python?' .format(name))
Python中.format的作用就是将每个参数替换致格式所在的位置。这之中可以有更详细的格式:
#对于浮点数‘0.333’保留小数点后三位: print('{0:.3f}' .format(1.0/3)) #基于关键词输出‘Thiago is reading A Bite of Pyhton' print('{name} is reading {book}' .format(name='Thiago', book='A Bite of Python'))
输出为:
0.333 Thiago is reading A Bite of Python
3.print总是会以\n (新一行)结尾
因此重复调用print会在相互独立的两行中打印;为了避免这一方式的换行,可以通过 end 指定其应该以‘空白’结尾:
print('a', end= '') print('b', end= '')
输出结果为:
ab
或者你可以指定end以‘空格’结尾:
print('a', end= ' ') print('b', end= ' ') print('c')
输出结果为:
a b c
4.字符串中的反斜杠(backslash\)
在一个字符串中,一个放置在某句结尾的\表示字符串将在下一行继续,但是并没有生成新的一行:
''this is the first line,\ but this is still the first line.''
相当于:
''this is the first line, but this is still the first line.''
反斜杠的作用:
物理行(physical line)是在编程时你所看到的内容,逻辑行(logical line)是Python 所看到的单个语句。 Python会假定每个物理行对应一个逻辑行。
如果你有一个非常长的语句,那么可以使用反斜杠将其拆分成多个物理行(但是他们任然是一个逻辑行),这被称作显式行链接(explicit line joining):
s='this is a string.\ and this continues that string.' print(s)
输出为:
this is a string. and this continues that string.
5.缩进
放置在一起的语句必须要有相同的缩进。每一组这样的语句被成为一个块,block
官方建议使用4个空格来缩进