【python】入门学习(五)
生活随笔
收集整理的這篇文章主要介紹了
【python】入门学习(五)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符串:
正索引,從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 = 0for 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?
轉載于:https://www.cnblogs.com/dplearning/p/3951711.html
總結
以上是生活随笔為你收集整理的【python】入门学习(五)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 逃少找师傅
- 下一篇: 莫干山生态板有什么可以推荐的吗?