字符串
字符串是 字符的序列 。字符串基本上就是一组单词。
单引号(')、双引号(") 、三引号('''或""") 、转义符(\)
●单引号(') 与 双引号(") 作用相同
●三引号('''或""")
利用三引号,可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双
引号。例如:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
●转义符
1. 用\'来指示单引号——注意这个反斜杠。现在你可以把字符串表示为'What\'s your name?'。
2. 在一个字符串中,行末的单独一个反斜杠表示字符串在下一行继续,而不是开始一个新的行。
例如:
"This is the first sentence.\
This is the second sentence."
等价于"This is the first sentence. This is the second sentence."
●自然字符串
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by \n"。
常用:一定要用自然字符串处理正则表达式。否则会需要使用很多的反斜杠。例如,后向引用符可以写成'\\1'或r'\1'
●Unicode字符串
Python允许处理Unicode文本——只需要在字符串前加上前缀u或U。例如,u"This is a Unicode string."。(以unicode编码方式 处理字符串)
记住,在你处理文本文件的时候使用Unicode字符串,特别是当你知道这个文件含有用非英语的语言写的文本。
for 循环
for i in range(1,5)等价于for i in [1, 2, 3, 4] 包含1,不包含5
同C/C++ for(int i = 1; i < 5; i++)
for i in rang(1,5,2) 等价 for i in [1,3]
例 for i inrange(1,5): print i
结果:
1
2
3
4
while..break..continue
#!/usr/bin/python
# Filename: continue.py whileTrue:
s = raw_input('Enter something : ') if s == 'quit': break iflen(s) < 3: continue print 'Input is of sufficient length'
# Do other kinds of processing here...
len(str)作用: 返回 字符串str的长度
目标:认识 raw_input() , rang(), len()等函数, while..break..continue ,if ..elif..else, for 等控制流语句