1 first_name = 'python'
2 name = first_name + 'testing'
3 print name
输出:pythontesting
重复(*)
1 name = 'python'
2 print name * 3
成员运算符(in)
判断一个字符串是否是另外一个字符串的子串,返回值True或False
1 name = 'python'
2 print 'x' in name //False
3 print 'on' in name //True
4 print 'On' in name //False,大小写敏感
for 语句,枚举字符串中的每个字符
name = 'python'
for c in name :
print c
p
y
t
h
o
n
示例,计算字符串中的元音字母字数
1 def vowles_count(s):
2 count = 0
3 for c in s:
4 if c in 'aeiouAEIOU':
5 count += 1
6 return count
7
8 print vowles_count('Hello World!')
字符串索引(index)
字符串中每个字符都用一个索引值(下标)
索引从0(向前)或-1(向后)开始
1 str = 'Hello World'
2
3 print str[2]
4 print str[-3]
5 print str[15]
6
7 l
8 r
9 Traceback (most recent call last):
10 File "<stdin>", line 1, in <module>
11 File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
12 execfile(filename, namespace)
13 File "C:/Users/weidan/Desktop/untitled0.py", line 12, in <module>
14 print str[15]
15 IndexError: string index out of range
1 import math
2
3 print "Hello {} good {} .".format(5,'DAY')
4
5 print math.pi
6
7 print 'PI is {:.4f}'.format(math.pi)
8
9 print 'PI is {:9.4f}'.format(math.pi)
10
11 print 'PI is {:e}'.format(math.pi)
12
13 结果:
14 Hello 5 good DAY .
15 3.14159265359
16 PI is 3.1416
17 PI is 3.1416
18 PI is 3.141593e+00
正则表达式:
判断一个人名(name)是否满足下列模式
Michael: name =='Michael'
以Mi开始: name[:2] == 'Mi'
包含cha字串: 'cha' in name
包含c?a字串:?
包含c*e字串:?
2.正则表达式用来描述字符串的模式:
. 表示任意字符
\d+ 表示一系列数字
[a-z]表示一个小写字母
示例:
1 import re
2
3 f=open('names.txt')
4 pattern = '(C.A)'
5
6 for line in f:
7 name = line.strip()
8 result = re.search(pattern,name)
9 if result:
10 print 'Find in {}'.format(name)
11 f.close
12
13 结果:
14 Find in ABULENCIA
15 Find in ACCARDI
16 Find in ACCARDO
17 Find in ACCIARDO
18 Find in ACCIARI
19 Find in ACCIAVATTI
20 Find in ACFALLE
21 ........