1. 程式人生 > >day04:常用的字符串內建函數

day04:常用的字符串內建函數

python 字符串

1、str.capitalize() 將字符串的第一個字母變成大寫,後續其他字母變成小寫。

>>> str = "kobego, KOBEGO"
>>> str.capitalize()
‘Kobego, kobego‘

2、str.center(width[, fillchar])將原字符串居中,並用指定的填充符填充至長度 width 的新字符串。

>>> str = "kobego"
>>> str.center(10,‘-‘)
‘--kobego--‘

3、 str.format()使用 {} 和 : 來代替格式符 %。

>>> "{0} {1}".format("Hello", "World!")
‘Hello World!‘

4、str.index(str, beg=0, end=len(string)) 與str.find(str,beg=0,end=len(string))都用於索引,但是前者未索引到相關內容會出現報錯,而後者則返回-1。

>>> str1 = "I Love Python"
>>> str2 = "Py"
>>> str1.index(str2,10)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    str1.index(str2,10)
ValueError: substring not found
>>> str1 = "I Love Python"
>>> str2 = "Py"
>>> str1.find(str2,10)
-1

5、str.isalnum()檢測字符串至少有一個字符並且所有字符都是字母或數字,返回True,否則返回 False。

>>> str3 = "kobego24"
>>> str3.isalnum()
True

6、str.join(sequence)將序列中的元素以指定的字符連接生成一個新的字符串,其中sequence 為要連接的元素序列。

>>> str = "*"
>>> seq = ("kobe","go")
>>> str.join(seq)
‘kobe*go‘

7、str.lower()將字符串中所有大寫字符為小寫。

>>> str1 = "I Love Python"
>>> str1.lower()
‘i love python‘

8、str.upper()將字符串中的小寫字母轉為大寫字母。

>>> str = "I Love Python"
>>> str.upper()
‘I LOVE PYTHON‘

9、str.partition(str)根據指定的分隔符將字符串進行分割,返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。

>>> str = "www.baidu.com"
>>> str.partition(".")
(‘www‘, ‘.‘, ‘baidu.com‘)

10、str.replace(old, new[, max])把字符串中的舊字符串用新字符串替換,且替換不超過 max 次。

>>> str = "aaaa"
>>> str.replace("a", "b", 2)
‘bbaa‘

11、str.split(str="", num=string.count(str))指定分隔符對字符串進行切片,若設置了num ,則將字符串分隔成 num 個子字符串。

>>> str = "www.baidu.com"
>>> str.split(".",2)
[‘www‘, ‘baidu‘, ‘com‘]

day04:常用的字符串內建函數