笨办法学Python - 习题8-10: Printing & Printing, Printing
Posted csyxf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了笨办法学Python - 习题8-10: Printing & Printing, Printing相关的知识,希望对你有一定的参考价值。
目录
1、习题 8: 打印,打印
学习目标:继续学习 %r 的格式化输出。
习题八中的练习代码是:
#! -*-coding=utf-8 -*-
formatter = "%r %r %r %r %r "
print formatter % (1, "hello", [1,2,3], (1,2,3), {"name":"jack"})
print formatter % ("one", "two", "three", "four", "five")
print formatter % (True, False, True, False, False)
print formatter % (
"I had this thing. ",
"That you could type up right. ",
"But it didn't sing. ",
"So I said doognight. ",
"Hello world."
)
上述代码的运行结果是:
C:Python27python.exe D:/pythoncode/stupid_way_study/demo8/Exer8-1.py
1 'hello' [1, 2, 3] (1, 2, 3) {'name': 'jack'}
'one' 'two' 'three' 'four' 'five'
True False True False False
'I had this thing. ' 'That you could type up right. ' "But it didn't sing. " 'So I said doognight. ' 'Hello world.'
Process finished with exit code 0
注意:上述代码说明两个点,一个是%r 的作用,是占位符,可以将后面给的值按原数据类型输出(不会变),支持数字、字符串、列表、元组、字典等所有数据类型。
还有一个需要注意的就是代码的最后一行:
print formatter % (
"I had this thing. ",
"That you could type up right. ",
"But it didn't sing. ",
"So I said doognight. ",
"Hello world."
)
'I had this thing. ' 'That you could type up right. ' "But it didn't sing. " 'So I said doognight. ' 'Hello world.'
最后输出的语句中既有单引号,也有双引号。原因在于 %r 格式化字符后是显示字符的原始数据。而字符串的原始数据包含引号,所以我们看到其他字符串被格式化后显示单引号。 而这条双引号的字符串是因为原始字符串中有了单引号,为避免字符意外截断,python 自动为这段字符串添加了双引号。
2、习题 9: 打印,打印,打印
学习目标:了解 的含义
习题九中的练习代码是:
#! -*-coding=utf-8 -*-
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan
Feb
Mar
Apr
May
Jun
Jul
Aug"
print "Here are the days: ",days
print "Here are the months: ",months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
C:Python27python.exe D:/pythoncode/stupid_way_study/demo9/Exer9-1.py
Here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
Process finished with exit code 0
上述代码有两个点需要注意下,一个是换行符 ,一个是注释符三引号。换行符就是避免代码过长影响阅读性而手动进行代码换行操作, 其实只是一个字符,类似的还有制表符 ,具体的更过的换行符知识请见下一题。
3、习题 10: 那是什么?
学习目标:了解 的含义,了解 ??的含义
首先来了解一下两种让字符串扩展到多行的方法:
- 换行符 (back-slash n ):两个字符的作用是在该位置上放入一个“新行(new line)”字符
- 双反斜杠(double back-slash) ??:这两个字符组合会打印出一个反斜杠来
3.1、转义序列:
下面介绍下再Python中常见的转义序列:
转义字符 | 描述 |
---|---|
?(在行尾时) | 续行符 |
? | 反斜杠符号 |
‘ | 单引号 |
" | 双引号 |
a | 响铃 |
退格(Backspace) | |
e | 转义 |