首頁  >  文章  >  後端開發  >  Python字串

Python字串

高洛峰
高洛峰原創
2016-10-29 11:18:151058瀏覽

如下學習python的字串用法。

print(dir(str))

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute ', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'caserefold', 'center ', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition ', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

如上是字串的所有方法,一個一個看,共44個

 

1.回第一個字母大寫

   capitalize(...)

      capitalize() -> string

>>>a = 'hello world'
>>> b = a.capitalize()
>>> print (b)
Hello world

2.依指定長度填入特定字元

    center(...)

      S.center(width[, fillchar]) -> string

>>> a = 'linux'
>>> print a.center(7,'h')
hlinuxh
>>> print a.center(8,'h')
hlinuxhh
>>> print a.center(9,'h')
hhlinuxhh

3.找出某個字串出現的次數

    count(...)

      S.count(sub[, start[, end]]) -> int

>>> a = "this is my dog, i love this dog and it's a good dog!"
>>> print a.count('dog')
3
>>> print a.count('dog',15)
2
>>> print a.count('dog',15,30)
0
>>> print a.count('dog',15,32)
1

4.以指定的格式編碼。預設編碼為字串編碼(適用於python2中處理中文)

    decode(...)

      S.decode([encoding[,errors]])     S.decode([encoding[,errors]]) ->object

re.指定後綴結尾,如果以指定後綴結尾傳回True,否則傳回False。可選參數"start"與"end"為檢索字串的開始與結束位置

    endswith(...)

    S.endswith(suffix[,start[, end]]) ->bool

b = 'strid'
>>> b.decode('utf-8')
u'strid'

.把字串中的 tab 符號('t')轉為空格,tab 符號('t')預設的空格數是8,tabsize -- 指定轉換字串中的 tab 符號('t')轉為空格的字元數。

    expandtabs(...)

    S.expandtabs([tabsize])-> string

>>> shaw = 'I am shaw,what\'s your name ?'
>>> shaw.endswith('?')
True
>>> shaw.endswith('w',7,9)
True
>>> shaw.endswith('w',7,8)
False

7.則檢查是否包含在指定範圍內,如果包含子字串,則傳回開始的索引值,否則傳回-1。

    find(...)

    S.find(sub [,start [,end]])-> int

>>> info = 'today is a good d\tay'
>>> print info.expandtabs()
today is a good d       ay
>>> print info.expandtabs(4)   # 把tab装换成4个空格
today is a good d   ay         
>>> printinfo.expandtabs(1)
today is a good d ay          # 把tab装换成1个空格

8.格式換字串輸出(方法與%相似,但可以指定順序)

    format(...)

    S.format(*args, **kwargs)-> string

>>> a = 'stivenwang'
>>> a.find('w')
6
>>> a.find('w',9)
-1
>>> a.find('w',9,11)
-1

9.偵測字符串中是否包含子字串 str ,如果存在,則傳回str在string中的索引值,如果指定beg(開始)和 end(結束)範圍,則檢查是否包含在指定範圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會回報一個異常(ValueError: substring not found)。

   index(...)

    S.index(sub [,start [,end]])-> int

>>> name = 'StivenWang'
>>> fruit = 'apple'
>>> print 'my name is {},I like {}'.format(name,fruit)
my name is StivenWang,I like apple
>>> print 'my name is {1},I like {0}'.format(fruit,name)
my name is StivenWang,I like apple
>>> print 'my name is {mingzi},I like{shuiguo}'.format(shuiguo=fruit,mingzi=name)
my name is StivenWang,I like apple

10.偵測是否由字母或數字組成字串。

    isalnum(...)

    S.isalnum() -> bool

>>> str1 = "this is string example....wow!!!"
>>> str2 = "exam"
>>> print str1.index(str2)
15
>>> print str1.index(str2,20)
Traceback (most recent call last):
  File "<input>",line 1, in <module>
ValueError: substringnot found报错

11.偵測字串是否只由字母組成

. -> bool

>>> a = &#39;123&#39;
>>> a.isalnum()
True
>>> b = &#39;shaw&#39;
>>> b.isalnum()
True
>>> c = &#39;shaw123&#39;
>>> c.isalnum()
True
>>> d = &#39;th 123&#39;
>>> d.isalnum()
False

12.偵測字串是否只由數字組成。

    isdigit(...)

    S.isdigit() -> bool

>> a = &#39;123&#39;
>>> a.isalpha()
False
>>> b = &#39;123shaw&#39;
>>> b.isalpha()
False
>>> c = &#39;shaw&#39;
>>> c.isalpha()
True
>>> d = &#39;sha w&#39;
>>> d.isalpha()
False

13.偵測字串是否由小寫字母組成。

    islower(...)

    S.islower() -> bool

>>> a = &#39;123&#39;
>>> a.isdigit()
True
>>> b = &#39;shaw&#39;
>>> b.isdigit()
False
>>> c = &#39;123shaw&#39;
>>> c.isdigit()
False

14.偵測字串是否只由空格組成。

    isspace(...)

    S.isspace() -> bool

>>> a = &#39; &#39;
>>> a.isspace()
True
>>> a = &#39;123&#39;
>>> a.isspace()
False
>>> a = &#39;shaw&#39;
>>> a.isspace()
False

15.检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

    istitle(...) 

    S.istitle() -> bool

>>> a = &#39;Shaw&#39;
>>> a.istitle()
True
>>> a = &#39;Shaw123&#39;
>>> a.istitle()
True
>>> a = &#39;123&#39;
>>> a.istitle()
False

16.检测字符串中所有的字母是否都为大写

    isupper(...)

      S.isupper() -> bool

>>> a = &#39;123&#39;
>>> a.isupper()
False
>>> a = &#39;Shaw&#39;
>>> a.isupper()
False
>>> a = &#39;Shaw123&#39;
>>> a.isupper()
False
>>> a = &#39;SHAW123&#39;
>>> a.isupper()
True

17.用于将序列中的元素以指定的字符连接生成一个新的字符串。

join(...)

    S.join(iterable) ->string

>>> a = &#39;-&#39;
>>> b = &#39;shaw&#39;
>>> print a.join(b)
s-h-a-w

18.返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

    ljust(...)

    S.ljust(width[, fillchar])-> string

    width -- 指定字符串长度

    fillchar -- 填充字符,默认为空格

>>> s = &#39;shaw&#39;
>>> s.ljust(10)
&#39;shaw      &#39;
>>> s.ljust(10,&#39;8&#39;)
&#39;shaw888888&#39;

19.转换字符串中所有大写字符为小写。

    Lower(...)

    S.lower() -> string

>>> s = &#39;PYTHON&#39;
>>> s.lower()
&#39;python&#39;
>>> s = &#39;PYTHON123&#39;
>>> s.lower()
&#39;python123&#39;

20.用于截掉字符串左边的空格或指定字符。

    lstrip(...)

    S.lstrip([chars]) ->string or unicode

>>> s = &#39;%%%shaw&#39;
>>> s.lstrip(&#39;%&#39;)
&#39;shaw&#39;
>>> s = &#39;   shaw&#39;
>>> s.lstrip()
&#39;shaw

123456    >>> s = '%%%shaw'>>> s.lstrip('%')'shaw'>>> s = '   shaw'>>> s.lstrip()'shaw'    

21.根据指定的分隔符将字符串进行分割(返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串)

    partition(...)

    S.partition(sep) ->(head, sep, tail)

>>> S = &#39;are you know:lilin is lowser&#39;
>>> S.partition(&#39;lilin&#39;)
(&#39;are you know:&#39;, &#39;lilin&#39;, &#39; is lowser&#39;)

22.把字符串中的 old(旧字符串)替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

    replace(...)

    S.replace(old, new[,count]) -> string

>>> S = &#39;shaw&#39;
>>> S.replace(&#39;sh&#39;,&#39;LI&#39;)
&#39;LIaw&#39;

23.返回字符串最后一次出现的位置,如果没有匹配项则返回-1。

    rfind(...)

    S.rfind(sub [,start[,end]]) -> int

    str -- 查找的字符串

    beg -- 开始查找的位置,默认为0

    end -- 结束查找位置,默认为字符串的长度。

>>> s = &#39;lilin is good li lao ban&#39;
>>> s.rfind(&#39;li&#39;)
14
>>> s.rfind(&#39;li&#39;,0,8)
2

24.返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。

    rindex(...)

    S.rindex(sub [,start[,end]]) -> int

    语法:

      str.rindex(str,beg=0 end=len(string))

>>> s = &#39;my name is shaw&#39;
>>> s.rindex(&#39;s&#39;)
11
>>> s.rindex(&#39;s&#39;,5,10)
9
>>> s.rindex(&#39;s&#39;,2,8)
Traceback (most recent call last):
  File "<input>",line 1, in <module>
ValueError: substring not found

25.返回的原/新字符串右对齐,且默认使用空格填充至指定长度(width)的新字符串。如果指定的长度(width)小于原字符串的长度则返回原字符串

    rjust(...)

    S.rjust(width[, fillchar])-> string

    语法:

      str.rjust(width[,fillchar])

       width -- 指定填充指定字符后新字符串的总长度.

       fillchar– 要填充的字符,默认为空格。

>>> s = &#39;sch&#39;
>>> s.rjust(20)
&#39;                 sch&#39;
>>> s.rjust(20,&#39;0&#39;)
&#39;00000000000000000sch&#39;
>>> s.rjust(20,&#39;H&#39;)
&#39;HHHHHHHHHHHHHHHHHsch&#39;

26.删除 string 字符串末尾的指定字符(默认为空格).

    rstrip(...)

    S.rstrip([chars]) ->string or unicode

    语法:

      str.rstrip([chars])

>>> s = &#39;shaw\n&#39;
>>> s.rstrip(&#39;\n&#39;)
&#39;shaw&#39;

27.通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔 num 个子字符串

    split(...)

    S.split([sep [,maxsplit]])-> list ofstrings

    语法:

   str.split(str="",num=string.count(str)).

>>> s = &#39;shaw\nlinux\nmac&#39;
>>> s.split(&#39;\n&#39;)
[&#39;shaw&#39;, &#39;linux&#39;, &#39;mac&#39;]
>>> s.split(&#39;\n&#39;,1)
[&#39;shaw&#39;, &#39;linux\nmac&#39;]

28.按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.

    splitlines(...)

    S.splitlines(keepends=False)-> list ofstrings

    语法:

      str.splitlines( num=string.count('\n'))

       num -- 分割行的次数。

>>> s = &#39;what\&#39;s your name?\n my name is shaw\n how old areyou?&#39;
>>> s.splitlines()
["what&#39;s your name?", &#39; my name is shaw&#39;, &#39; how old areyou?&#39;]
>>> s.splitlines(1)
["what&#39;s your name?\n", &#39; my name is shaw\n&#39;, &#39; how old areyou?&#39;]
>>> s.splitlines(3)

29.用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end指定值,则在指定范围内检查。

    startswith(...)

    S.startswith(prefix[,start[, end]]) ->bool

    语法:

    str.startswith(str,beg=0,end=len(string))

    str -- 检测的字符串。

    strbeg -- 可选参数用于设置字符串检测的起始位置。

    strend -- 可选参数用于设置字符串检测的结束位置。

>>> s = &#39;my name is shaw&#39;
>>> s.startswith(&#39;my&#39;)
True
>>> s.startswith(&#39;my&#39;,10,15)
False

30.用于移除字符串头尾指定的字符(默认为空格)。

    strip(...)

    S.strip([chars]) ->string or unicode

>>> s = &#39;my name is sam&#39;
>>> s.strip(&#39;m&#39;)
&#39;y name is sa&#39;

31.用于对字符串的大小写字母进行转换(小写转大写,大写转小写)

    swapcase(...)

    S.swapcase() -> string

>>> s = &#39;stiven&#39;
>>> s.swapcase()
&#39;STIVEN&#39;
>>> s = &#39;SHAW&#39;
>>> s.swapcase()
&#39;shaw&#39;

32.返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写。

    title(...)

    S.title() -> string

>>> s = &#39;my name is shaw&#39;
>>> s.title()
&#39;My Name Is Shaw&#39;

33.根据参数table给出的表(包含 256 个字符)转换字符串的字符, 并返回翻译后的字符串。要过滤掉的字符放到del 参数中

    translate(...)

    S.translate(table [,deletechars])->string

    语法:

      str.translate(table[, deletechars])

       table -- 翻译表,翻译表是通过maketrans方法转换而来。

      deletechars -- 字符串中要过滤的字符列表。

>>> from string import maketrans
suchas = maketrans(&#39;sm&#39;,&#39;@$&#39;)
>>> s = &#39;this is sam\&#39;s dog&#39;
>>> s
"this is sam&#39;s dog"
>>> s.translate(suchas)
"thi@ i@ @a$&#39;@ dog"
>>> s.translate(suchas,&#39;dog&#39;) 去除d,o,g字符
"thi@ i@ @a$&#39;@ "

34.将字符串中的小写字母转为大写字母

    upper(...)

    S.upper() -> string

>>> s = &#39;sam&#39;
>>> s.upper()
&#39;SAM&#39;
>>> s = &#39;23sam&#39;
>>> s.upper()
&#39;23SAM&#39;
>>> s = &#39;23s am&#39;
>>> s.upper()
&#39;23S AM&#39;

作者:terry
blog:http://www.cnblogs.com/kkterry/
Weibo:http://weibo.com/kkterry
E-mail:doubleginger@163.com
欢迎转载,还请标明出处

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn