第6章 字符串
一、字符串索引
1、假设有字符串s=”apple”,那么可以通过索引去访问其中的字符,Python通过方括号来标识字符串索引,索引从0开始:s[0]=”a”,s[1]=”p”,s[2]=”p”,s[3]=”l”,s[4]=”e”。
2、Python也支持使用负数索引,比如如果要访问字符串s的最后一个字符,那么按照正索引则可以通过s[len(s)-1]访问,也可以通过s[-1]来访问最后一个字符,这就是负数索引,从字符串最后一位到第一位对应的索引数字为-1,-2…,-[len(s)]。
3、使用for循环访问字符串中的字符
下例程序计算给定字符串的字符编码总和:
#codesum.py
def codesum1(s):
"""Returns the sums of the
character codes of s.
"""
total=0
for c in s:
total=total+ord(c)
return total
myinput=input("please input a string:")
print("你输入字符串的字符编码和为:"+str(codesum1(myinput)))
上述代码中直接通过”for c in s”来进行索引,每次c迭代为s中的字符,表达式简洁明了,ord()函数功能是返回字符的编码数值。
如果使用正索引则如下,表达方面相对显得更复杂:
#codesum1.py
def codesum1(s):
"""Returns the sums of the
character codes of