字符串:
正索引,从0开始 和 负索引,从-1开始
>>> s = ‘apple‘ >>> s[0] ‘a‘ >>> s[1] ‘p‘ >>> s[2] ‘p‘ >>> s[3] ‘l‘ >>> s[4] ‘e‘ >>> s[-1] ‘e‘ >>> s[-2] ‘l‘ >>> s[-3] ‘p‘ >>> s[-4] ‘p‘ >>> s[-5] ‘a‘
在for循环中遍历字符串只需要:
for c in s:
#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
ord():获取字符的编码 Unicode
chr():通过编码获取字符
>>> ord(‘喜‘) 21916 >>> chr(21916) ‘喜‘
转义字符,用反斜杠:\\ , \‘, \", \n, \r, \t
>>> print(‘a\nb\nc\n‘) a b c
字符串切片:
>>> food = ‘apple pie‘ >>> food[0:5] ‘apple‘
默认切片的第一个数是0,最后一个数是字符串末尾的索引+1,也可以使用负数索引,不过很难懂
>>> food[:5] ‘apple‘ >>> food[6:] ‘pie‘
获取文件扩展名:
#extension.py def get_ext(fname): """Return the extension of file fname.""" dot = fname.rfind(‘.‘) if dot == -1: return ‘‘ else: return fname[dot+1:]
>>> get_ext(‘apple.in‘) ‘in‘
标准字符串函数:
s.find(t) #从左向右查找t,返回位置,没有返回-1
s.rfind(t) #同上,从右向左查找
s.index(t) #同s.find(t),但没有找到会引发错误
s.rindex(t) #同上,从右向左查找
>>> s.find(‘p‘) 1 >>> s.rfind(‘p‘) 2
正则表达式re:
xy? x 、xy
x|y x、y
x* ‘ ‘、x、xx、xxx、xxxx...
x+ x、xx、xxx、xxxx....
#funny.py import re def is_funny(s): return re.match(‘(ha)+!+‘,s) != None
>>> is_funny(‘hahahahahaha!!!‘) True
时间: 2024-10-14 22:34:05