Python (三) 字符串

python (三) 字符串


Python版本:3.6.3

官方說明 https://docs.python.org/3/library/string.html

2.5 字符串 str

str使用引號括起來,可以是單引號、雙引號、三引號,但必須成對匹配使用。來幾個小例子:

s = 'hello'
d = "hello world"
t1 = """hello world 1"""
t2 = '''hello world 2'''

print(s,d,t1,t2)

輸出如下:

hello hello world hello world 1 hello world 2

那他們有什麼區別呢?三引號可以用來包含多行字符串,單、雙引號則不行。

t = """hello\n\n
world
    yes
        no"""
print(t)

輸出如下(hello和world之間有兩空行):

hello


world
    yes
        no

另外,python還支持一種叫做原始字符串的表達方式,在字符串前面加r

t = r"""hello\n\n
world
    yes
        no"""
print(t)

輸出如下(hello和world之間沒有空行):

hello\n\n
world
    yes
        no

這就是原始字符串和普通字符串的區別,我們在shell中可以看到原始字符串的表達,它內部將轉義符號進行了轉義

>>>t = r"""hello \n world"""

>>>t
'hello \\n world'

>>>print(t)
hello \n world

類似的,我們可以使用str()來轉化爲str類型。

字符串的相關方法

    1. 統計查找

s = "\thello world "
print(s.count('l'))         # 指定字符串出現的次數
print(s.index("world"))     # 第一次出現的下標
# print(s.index("n"))       # 如果字符串中不包含此字符串,則拋出:ValueError: substring not found
print(s.find("n"))          # 如果字符串中不包含此字符串,則返回 -1
print(s.rfind("l"))         # 從右往左查找,如果字符串中不包含此字符串,則返回 -1

輸出如下:

3
7
-1
10

    2. 去兩邊的字符

a = s.strip()               # 默認去掉字符串兩邊的空白字符,並不改變原始字符串的值
b = s.lstrip()              # 默認去掉左邊的空白字符
c = s.rstrip()              # 默認去掉右邊的空白字符
print(s)
print(a)

輸出如下:

    hello world 
hello world
hello world         #[world後面有一個空格]
    hello world     #[world後面沒有空格]

    3. 判斷首尾

s = "helLO WoRld"
print(s.startswith("hel"))      # 是否以指定字符串開頭
print(s.endswith("world"))      # 是否以指定字符串結尾

輸出如下:

True
False

    4. 大小寫

s = "helLO WoRld"
a = s.capitalize()      # 首字母大寫,其餘小寫,非英文字母的大小寫不會轉換
b = s.upper()           # 全部大寫,非英文字母的大小寫不會轉換
c = s.lower()           # 全部小寫,非英文字母的大小寫不會轉換
d = s.casefold()        # 忽略大小寫,其實就是全部轉化爲小寫,Unicode 編碼中凡是有對應的小寫形式的,都會轉換
e = s.swapcase()        # 交換大小寫
print(a)
print(b)
print(c)
print(d)
print(e)

輸出如下:

Hello world
HELLO WORLD
hello world
hello world
HELlo wOrLD

    5. 格式化

s = "hello\tworld"
a = s.center(20, "_")   # 將字符串長度擴展爲指定長度,並且居中,兩邊用指定字符串填充
                        # 如果指定的長度小於字符串長度,則返回原字符串。
b = s.expandtabs(4)     # 將製表符替換爲空格,參數爲空格個數
c = "{0} + {1} = {2}".format(1, 3, 1 + 3)   # 位置參數格式化
                                            # 可以與關鍵字參數格式化混用,但是位置參數必須放在關鍵字參數之前
#c = "{0} + {1} = {sum}".format(1, 3, sum=1 + 3)    # 關鍵字參數
d = "{num1} + {num2} = {sum}".format_map({"num1": 1, "num2": 5, "sum": 1 + 5})
                        # format_map的參數是一個Mapping[str,Any]對象,因此字典的key必須是str,value爲任意類型
e = s.zfill(20)         # 左邊用0填充,填充到指定長度
f = s.ljust(20,"0")     # 將字符串調整到左邊,右邊用指定字符串(默認爲空格)填充到指定長度
g = s.rjust(20,"0")     # 將字符串調整到右邊,左邊用指定字符串(默認爲空格)填充到指定長度
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)

輸出如下:

____hello   world_____
hello   world
1 + 3 = 4
1 + 5 = 6
000000000hello  world
hello   world000000000
000000000hello  world

字符串格式化符號及其說明

符號 說明
%c 格式化字符及其ASCII碼
%s 格式化字符串
%d 格式化整數
%o 格式化無符號八進制數
%x 格式化無符號十六進制數(小寫)
%X 格式化無符號十六進制數(大寫)
%f 格式化定點數,可指定小數位數
%e 格式化科學計數法定點數(小寫)
%E 格式化科學計數法定點數(大寫)
%g 自動根據值判斷使用%f或者%e
%G 自動根據值判斷使用%f或者%E

使用上述符號格式化時,需要用%格式化,並且多個格式化時,需要用()將參數變爲元組

print("%c" % 97)
print("%s" % "hello")
print("%d %o" % (10,10))

輸出結果:

a
hello
10 12 

    6. 邏輯判斷

s = "123"
print(s.isalnum())      # 是否所有字符都是字母或者數字

print(s.isnumeric())    # 是否所有字符都是數字
print(s.isdecimal())    # 是否所有字符都是數字
print(s.isdigit())      # 是否所有字符都是數字,並且至少有一個字符

print(s.isalpha())      # 是否所有字符都是字母,並且至少有一個字符
print(s.islower())      # 是否所有字符是都小寫,並且至少有一個字符
print(s.isupper())      # 是否所有字符都是大寫,並且至少有一個字符

print(s.isprintable())  # 是否所有字符都可打印或者s爲空
print(s.isspace())      # 是否所有字符都是空白字符,並且至少有一個字符
print(s.isidentifier()) # 是否是合法的標誌名
print(s.istitle())      # 是否是標題,即每個單詞以大寫字母開頭,單詞的其餘字母爲小寫

輸出如下:

True

True
True
True

False
False
False

True
False
False
False

    7. 聯合分割

s = "a good day today. \n nice day"     
a = s.split("day")                      # 返回一個按指定字符串分割後的列表
                                        # 如果指定了maxsplit,則最多分割maxsplit次,即返回的列表長度最多爲maxsplit+1
b = s.rsplit("day")                     # 同上,從右往左分割,只是在指定maxsplit時可能返回的結果可能與split()返回的不一樣
c = s.splitlines()                      # 將字符串分割按行分割,返回一個列表
d = s.partition("day")                  # 分塊,從左往右
e = s.rpartition("day")                 # 分塊,從右往左

f = "-".join(["2017","12","12"])        # 用字符串連接可迭代對象的每一個元素(元素必須是字符串類型)

print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

輸出結果:

['a good ', ' to', '. \n nice ', '']
['a good ', ' to', '. \n nice ', '']
['a good day today. ', ' nice day']
('a good ', 'day', ' today. \n nice day')
('a good day today. \n nice ', 'day', '')
2017-12-12
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章