练习6-字符串和文本
- 字符串和文本练习程序
- 附加练习
# -*-coding: utf-8 -*-
x = "There are %d types of people." % 10
# 数字10用%d格式化带到字符串中去
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
# 将binary和do_not用%s格式化带到字符串中去
print x
print y
print "I said: %r." % x
# %r的格式将x带进来,注意%r和%s的区别是。%r会把所有内容都带进来,包括字符串中的引号
print "I also said: '%s'." % y
# %s的格式将字符串带进来
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
#%r的格式将False带进来,注意这里false并不是一个字符串,所以带进来没有引号
w = "This is the left side of..."
e = "a string with a right side."
print w + e
将两个字符串拼接
运行结果
PS F:\python大师\习题> 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?! False
This is the left side of...a string with a right side.
附加练习
2.Find all the places where a string is put inside a string. There are four places.
y = "Those who know %s and those who %s." % (binary, do_not)
#这里2个
print "I said: %r." % x
#这里1个
print "I also said: '%s'." % y
#这里1个
3Are you sure there are only four places? How do you know? Maybe I like lying.
非要再两个出来的话也是可以得,print "I also said: '%s'." % y这里调用了y,而y本身又会去调用(binary, do_not)这两个,所以y重新去调用的时候,又多了2个
4Explain why adding the two strings w and e with + makes a longer string.
谷歌是查了一下,其实就是调用了join这个方法进行的字符串拼接
print ''.join((w,e))