python初学_2

   这次主要是记下自己学python时的错误及心得体会(针对《笨方法学python》前十个习题),主要是关于python2中的打印知识。首先是关于引号的问题,python2中,单引号与双引号作用貌似是一样的,但是由于各人的编程风格不同,所以使用起来可能会略有差别,比如,有些人喜欢用单引号括住单个字符,用双引号括住字符串;但python不允许单引号嵌套单引号,也不允许双引号嵌套双引号,但是允许两种引号相互嵌套。python中三引号的形式用来输入多行文本,也就是说在三引号之间输入的内容将被原样保留,之中的单号和双引号不用转义,其中的不可见字符比如/n和/t都会被保留,这样的好处是你可以替换一些多行的文本。
print """
\tThere's something going on here.
\n\tWith the three "double-quotes".
\tWe'll be able to type as much as we like.
\tEven 4 lines if we want, or 5, or 6.
"""

运行结果

2.一些格式化字符串:
%s 字符串 (采用str()的显示,一般用这个打印字符串)

%r 字符串 (采用repr()的显示,只有在想要获取某些东西的debug信息时才用,打印包含中文字符的字符串会乱码)

%c 单个字符

%b 二进制整数

%d 十进制整数

%i 十进制整数

%o 八进制整数

%x 十六进制整数

%e 指数 (基底写为e)

%E 指数 (基底写为E)

%f 浮点数

%F 浮点数,与上相同

%g 指数(e)或浮点数 (根据显示长度)

%G 指数(E)或浮点数 (根据显示长度)

formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing",
    "So I said good night."
)

这里写图片描述
这个也是python2打印比较特殊的地方,要特殊掌握!

注意:写python时,单行字符最好不要超过80个字符,保持好的代码规范!多写注释也是好的程序员必备的好习惯!!坚持也很重要!!!


猜你喜欢

转载自blog.csdn.net/wayne17/article/details/74905534