Learn Python The Hard Way学习(6) - 字符串和文本


我们已经学习了字符串了,但是还不知道他们能干什么,下面的练习我会建立一些更加复杂的字符串变量,你可以知道他们是做什么的,首先解释下什么是字符串。

字符串就是你想展示别人的文本,或者程序要输出的信息。当你使用"或者'包含一段文本的时候,Python就知道这是一段字符串。前面我们已经用print打印了很多字符串了。

字符串可能包含格式符,就是%后面加个字母。如果包含多个格式符的话,后面的变量要用一个()包含并且用,号分隔。比如你要告诉我一个购物清单:“我要买牛奶,鸡蛋,面包和汤”,程序就是(milk, eggs, bread, soup)。

程序员喜欢用一下短而模糊的变量名,是为了节约时间,下面我们就这样写一下,以便以后看到这些简单的变量名我们也能读懂。
[python] 
1. x = "There are  %d types of people." % 10 
2. binary = "binary" 
3. do_not = "don't" 
4. y = "Those who know %s and those who %s." % (binary, do_not) 
5.  
6.  
7. print x 
8. print y 
9.  
10.  
11. print "I said: %r." % x 
12. print "I also said: '%s'." % y 
13.  
14.  
15. hilarious = False 
16. joke_evaluation = "Isn't that joke so funny?! %r" 
17.  
18.  
19. print joke_evaluation % hilarious 
20.  
21.  
22. w = "This is the left side of ..." 
23. e = "a string with a right side." 
24.  
25.  
26. print w + e 

运行结果
root@he-desktop:~/mystuff# 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.
root@he-desktop:~/mystuff#

加分练习
1. 给每行都加上注释。

2. 找出所有在字符串中插入字符串的地方,有四个地方。
• y = "Those who know %s and those who %s." % (binary, do_not)  这里是两个地方。
• print "I said: %r." % x
• print "I also said: '%s'." % y

3. 你怎么知道只有这四个地方的?或者不只四个呢?
只有四个地方,因为字符串是用单引号或者双引号包括起来的。

4. 解释一下+号为什么能把两个字符串合并。

 作者:lixiang0522

相关内容

    暂无相关文章

评论关闭