python-习题6~10

本教程通过实例演示如何在Python中处理字符串,包括字符串拼接、转义字符的使用及格式化输出等关键技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

习题  6:字符串(string)和文本

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)  #定义变量,将要输出的内容存放到变量x,y,
                                                                   #   binary,do_not.

print x
print y

print "I said: %r."%x          #  ①
print "I also said:'%s'."%y        #  ②

hilarious = False
joke_evaluation = "Isn't that joke so funny?!%r"     # 定义变量

print joke_evaluation %hilarious    #  ③ ④

w = "This the left side of……"   
e = "a string with a right side."

print w + e    #  ⑤

运行结果:

There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'.   #  变量x中的""变成了''
I also said:'Those who know binary and those who don't.'.
Isn't that joke so funny?!False
This the left side of……a string with a right side.  #   两变量相加合成一句了。

语法总结:

1.  用“+”号可以把两个字符串连起来组成一个更长的字符串(运算符重载)。

2.  当变量x里存放的字符串含有“”时,输出时不需要再加“”。

3.  输出后变量x中的“”变成了''.

 

加分习题:

1.  给以上程序加注释。(已加)

2.  找到所以字符串包含字符串的位置,总共有四个位置。(如上:用序号①②③④⑤标注)

3.  你确定只有四个位置吗?你怎么知道的?没准我在骗你呢。(作者真调皮)

4.  解释一下为什么w和e用 + 连起来就可以生成一个更长的字符串。

       运算符重载。具体说来,每个变量在Python中都是以对象形式存在的,即都是继承于Object。而Object则具有object.__add__(self, other)这样一个方法。每当处理x+y这一个表达式的时候,将会调用x.__add__(y)。另外为了交换律,还有__radd__方法,也就是用来处理y+x,这样会调用y.__radd__(x)

所以我们也可以自己重载+,比如:

class Free:
    def __init__(self, info):
        self.info = info   
    def __add__(self, moreinfo):
        return str(self) + moreinfo
    def __radd__(self, moreinfo):
        return moreinfo + str(self)
    def __str__(self):
        return self.info

Free这个Class,便得以直接成为+操作符的左/右参数。

正如richardzhiming所说,a+b是低效的,这是基于大量的+操作所讨论的。这是因为String是一个不可变的对象,你并不是真的把字符串b加到字符串a这个对象后面,而是需要创建一个新的对象,然后把a和b copy进去。因此当你大量进行+之时,你会创建许许多多临时的String对象。''.join(str_list)更好,则是因为,字符串的创建和拷贝是一次完成,而不需要创建很多String对象。

关于字符串连接具体的实验和更深入的探讨,可以参考:
Efficient String Concatenation in Python
The Python String Concatenation Shootout

另外,程序的优化的关键并不在于每个细节都优化到,而是优化整体的瓶颈,所以题主也不是一定要记住每一个细微的优化技巧。但是了解具体的实现细节,对于掌握语言,是很有意义的。

答案内容来自:http://segmentfault.com/q/1010000003933405

 

习题  7:更多的打印

print "Mary had a little lamb."
print "Its fleece was white as %s."% 'snow'  # 字符串变量用单引号括起来,区别于C
print "And everywhere that Mary went."
print "."* 10 # what'd that do?  ->输出10个“.”

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  # 运算符重载

运行结果:

Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
cheese Burger

语法总结:

1.  字符串变量用单引号  ' '.

2.  运算符重载:end(1~12)组成长字符串。

3.  倒数第三行的逗号去掉结果会换行。

练习  8:打印,打印

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 % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight,"
    )

运行结果:

1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight,'

语法总结:

1.  最后一行输出结果既含有单引号又含有双引号,

->字符串里面没有单引号时且外面是双引号时,输出单引号;

(外层是单引号时,输出时无引号;)

    里层有单引号时,输出外层双引号。

 

 

习题  9:打印, 打印, 打印

# Here's some new strange stuff,remenber type it exactly.

days = "Mon Tue Wed Thu Fri Sat Sum"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print "Here are the days:",days
print "Here are the months:",months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.
"""

运行结果:

Here are the days: Mon Tue Wed Thu Fri Sat Sum
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.

语法:

 

习题  10:

将双引号和单引号转义,让 Python 将引号也包含到字符串里边去,例:

"I am 6'2\" tall,"  #将字符串中的双引号转义
'I am 6\'2" tall."  #将字符串中的单引号转义

另:用三引号转义,也就是" " ",例:

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = """
I'll do list:
\t* Cat food
\t*Fishies
\t*Catnip\n\t* Grass
"""

print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

运行结果:

	I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.

I'll do list:
	* Cat food
	*Fishies
	*Catnip
	* Grass

语法总结:

1.  "\t"制表符,缩进4个空格。

2.  三引号""",转义,可以放入任意多行文字。

加分题:

1.  另有Python转义字符:

在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表:

原始字符串

有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和R来定义原始字符串。如:

print r'\t\r'

实际输出为“\t\r”。

 

转义字符描述
\(在行尾时)续行符
\\反斜杠符号
\'单引号
\"双引号
\a响铃
\b退格(Backspace)
\e转义
\000
\n换行
\v纵向制表符
\t横向制表符
\r回车
\f换页
\oyy八进制数yy代表的字符,例如:\o12代表换行
\xyy十进制数yy代表的字符,例如:\x0a代表换行
\other其它的字符以普通格式输出

内容来自:http://www.cnblogs.com/allenblogs/archive/2011/04/28/2031477.html

2.  使用三个单引号(' ' ')和三个双引号,效果是一样的。

3.  将转义序列和格式化字符串放到一起,创建一种更为复杂的格式。

 

4.  %r  打印出来的是你写在脚本里的内容,而%s  打印的是你应该看到的内容(换句话说%r会打印任意你放入的内容)

 

 

 

 

 

 

 

转载于:https://my.oschina.net/8824/blog/786686

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值