笨办法学python习题6 字符串和文本
程序员文章站
2022-06-15 18:44:50
...
这次的习题学习格式化控制符,在下面的代码中。
字符串中的格式化字符串类似规一个规定好只能盛放特定液体的罐子。牛奶瓶子装牛奶、茶杯装茶
%d:装10进制的整形数据
%s:装字符串类型的数据
%r : 装任何类型的数据
x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." %(binary , do_not)
print x
print y
print "I said : %r." %x
print "I also said '%s' " %y
hilarious = True
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of ..."
e = "a string with a right side."
print w + e
输出结果为:
mystuff simengred$ python ex6.py
There are 10 types of people.
Those who know binary and those who don't.
I said : 'There are 10 types of people.'.
I also said 'Those who know binary and those who don't.'
Isn't that joke so funny?! True
This is the left side of ...a string with a right side.
特别注意的2点:
1,%s打印的数据是“ ”(引号)内部的内容,要想打印出引号,需要在%s两侧加上引号:
print "I also said '%s' " %y
而%r 则是无论什么都打印,不过双引号会编程单引号。
不过%r 用来做调试的使用
2,格式化控制符的个数应该与参数保持一致,不然运行程序的时候会报错。