格式化输出字符串

1、格式化方法
有时候我们会想要从其他信息中构建字符串。这正是format()方法大有用武之地的地方。
将以下内容保存为文件  str_format.py  :
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))

print('Why is {0} playing with that python?'.format(name))


# 对于浮点数 '0.333' 保留小数点(.)后三位

print('{0:.3f}'.format(1.0/3))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义 '___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Swaroop wrote A Byte of Python'

print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))


2、 end=''  不换行打印

如: print('a', end='')

   print('b', end='')

输出结果如下:
ab

3、转义序列

想象一下,如果你希望生成一串包含单引号( '  )的字符串,你应该如何指定这串字符串?
例如,你想要的字符串是  "What's your name?"  。你不能指定  'What's your name?'  ,因为这
会使 Python 对于何处是字符串的开始、何处又是结束而感到困惑。所以,你必须指定这个单
引号不代表这串字符串的结尾。这可以通过 转义序列(Escape Sequence) 来实现。你通过
\  来指定单引号:要注意它可是反斜杠。现在,你可以将字符串指定为  'What\'s your
name?'  。
另一种指定这一特别的字符串的方式是这样的:  "What's your name?"  ,如这个例子般使用
双引号。类似地, 你必须在使用双引号括起的字符串中对字符串内的双引号使用转义序列。
同样,你必须使用转义序列  \\  来指定反斜杠本身。
如果你想指定一串双行字符串该怎么办?一种方式即使用如前所述的三引号字符串,或者你
可以使用一个表示新一行的转义序列—— \n  来表示新一行的开始。下面是一个例子:
'This is the first line\nThis is the second line'
另一个你应该知道的大有用处的转义序列是制表符: \t  。实际上还有很多的转义序列,但
我必须只在此展示最重要的一些。
还有一件需要的事情,在一个字符串中,一个放置在末尾的反斜杠表示字符串将在下一行继
续,但不会添加新的一行。来看看例子:
"This is the first sentence. \
This is the second sentence."
相当于
"This is the first sentence. This is the second sentence."

猜你喜欢

转载自blog.csdn.net/gxyl1806/article/details/80681143