
正文
python formatters 与字符串 小结 (python 2)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
最近学习python 2 ,觉得有必要小结一下关于字符串处理中的formatters,
转载请声明本文的引用出处:仰望大牛的小清新
0.%进行变量取值使用的时机
在python中,如果我们只是需要在字符串中输出变量的内容,我们可以无需使用formatters,例如:
# python 2
#以下代码输出 days 变量的值,没有使用到formatters,因此也不需要使用%
days = "Mon Tue Wed Thu Fri Sat Sun"
print "Here are the days: " , days, ".\n These days are perfect."
当我们使用到了formatters的时候,我们才需要%在字符串后取变量的值。如果取一个变量,则只需 % 变量名,如果是多个变量,则需要 %(变量1,变量2,....)
例如:
#python 2
#取1个变量的值
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %s." % months #取多个变量的值,并接一个字符串
print "The date is: %s %s." % (month, day), "And she will marry to Lu."
1.%s和%r的区别:
对于非字符串类,%s使用str() 方法,而%r使用repr()方法
对于字符串而言,却别就在于,'%s' 才等价于 %r,换句话说,%r会自动给字符串加上单引号,这是由于%r本身 “还原对象”的特性决定的
因此,%r适用于debug,而%s更适用于输出字符串,即使字符串之间可嵌套。
%r产生的,是 “raw presentation”的版本,举例如下
%r用于调试的例子:
# 如果我们使用%s,则会输出换行符
# 但如果我们使用%r,则会输出\n,而不换行
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" %months
2.python的字符串操作当中支持字符串的嵌套
例如
# python 2 的示例
a_str = "Your name is %s."
my_name = " 张三 "
print a_str % my_name
更进一步,我们可以将formatters定义为一个变量,使用%r来进行调试性的输出
例如,下面这个例子可以调试4个参数的值
# -*- coding: utf-8 -*-
# from __future__ import unicode_literals formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, True, False)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right",
"But it didn't string.",
"So I said goodnight."
)
而我们也可以利用字符串*的方法使得调试输出的参数数目可变
例如
#num为需要调试的参数的数目
num = 5
formatter = "%r " * num
print formatter % (
"one", "two", "three"
,"four", "five"
)
3. 一个print 语句 执行后默认会换行,在print后面加上逗号,可以使得print不进行换行
例如
#这两据print将会输出到同一行
#将第一个print后面的逗号去掉后,将会换行
print "And everywhere that Marry went.",
print "I'm here."
4.字符串之间的+操作起到连接字符串的作用
例如
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r" #watch that comma at the end. try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
5.字符串的*一个数字n,表示将该字符串连续输出n遍
例如
#下面两行的行为等价,都是在一行中连续输出10个你好
print 10 * "你好"
print "你好" * 10
6.很长的字符串可以用三个双引号开头,跨行写,并以三个双引号结尾
例如
# python 2
# 输出跨行的很长的字符串
print """
There's somthing going on here.
With the three double-quotes.
We'll be able to type as mych as we like.
Even 4 lines if we want, or 5, or 6
"""
同时,需要注意的是,在""" 之间 """的内容的换行和我们的输入换行是一样的,下面的例子说明了这一点
例如
# python 2
# 在三个双引号之间的多行文本,在输出
#的换行中,与文本本身的换行一致,不需要专门写\n
#例如下面例子中前几行和最后一行写了\n的换行是等效的 fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print fat_cat
7.\r是回车符,用于将光标置于行首,将print后面加上逗号,即可以将所有的回车连起来,这样可以起到在一行不断刷新输出的效果
例如
# 一个有趣的代码实验,%r是回车,用于回到行首
# 因此%r可以用于刷新符号的代码
while True:
for i in ["/","-","|","\\","\""]:
print "%s\r" % i, #注意行尾的逗号,保证了输入在同一行






