練習(xí)6-字符串和文本
- 字符串和文本練習(xí)程序
- 附加練習(xí)
# -*-coding: utf-8 -*-
x = "There are %d types of people." % 10
# 數(shù)字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帶進(jìn)來(lái),注意%r和%s的區(qū)別是。%r會(huì)把所有內(nèi)容都帶進(jìn)來(lái),包括字符串中的引號(hào)
print "I also said: '%s'." % y
# %s的格式將字符串帶進(jìn)來(lái)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
#%r的格式將False帶進(jìn)來(lái),注意這里false并不是一個(gè)字符串,所以帶進(jìn)來(lái)沒(méi)有引號(hào)
w = "This is the left side of..."
e = "a string with a right side."
print w + e
將兩個(gè)字符串拼接
運(yùn)行結(jié)果
PS F:\python大師\習(xí)題> 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.
附加練習(xí)
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個(gè)
print "I said: %r." % x
#這里1個(gè)
print "I also said: '%s'." % y
#這里1個(gè)
3Are you sure there are only four places? How do you know? Maybe I like lying.
非要再兩個(gè)出來(lái)的話也是可以得,print "I also said: '%s'." % y這里調(diào)用了y,而y本身又會(huì)去調(diào)用(binary, do_not)這兩個(gè),所以y重新去調(diào)用的時(shí)候,又多了2個(gè)
4Explain why adding the two strings w and e with + makes a longer string.
谷歌是查了一下,其實(shí)就是調(diào)用了join這個(gè)方法進(jìn)行的字符串拼接
print ''.join((w,e))