python 字符串操作

字符串

字符串本質是字符序列。Python的字符串是不可修改的。無法對原字符串進行修改,但是可以將字符串的一部分賦值到新字符串,來達到相同的修改效果。

字符串運算+和*

+ 字符串的拼接   
* 字符串的複製    

使用[]提取字符

在字符串名後面添加[],並在括號裏指定偏移量可以提取該位置的單個字符。注意:第一個字符的便宜量爲0,下一個是1,以此類推。最後一個字符的偏移量可以使用-1來表示,這樣就不必從頭數到尾。偏移量從右向左緊接着爲-2、-3,以此類推。
注意:如果指定的字符串超過了字符串的長度,會得到一個錯誤提示:string index out of range.

再次注意:由於字符串不可修改,所以試圖通過[]去修改字符串的行爲是錯誤的。如果我們需要改變字符串,需要使用一些字符串函數,例如str.replace()。

使用[start:end:step]切片

[:] 提取從開頭到結尾的整個字符串;
[start:] 提取從start開始到結尾的所有字符串;
[:end] 從開頭提取到end-1之間所有字符;
[start:end] 從start提取到end-1;
[start:end:step] 從start到end-1,每step個字符提取一個.

字符串的操作

len() 獲得長度

    s1 = "abcde"
        print(len(s1))

spli() 分割 字符串專用

s = "aa bb cc dd,ee"
s2 = s.split(" ,")  # split函數是string對象專有的
print(s2)

find()從左向右找指定的字符在字符串的位置 若不存在 返回-1

rfind() 從右向左

    s = "acdf123slkj123sdknf"
    pos = s.find("123")
    print("pos = %d" % pos)
    pos2 = s.rfind("123")
    print("pos2 = %d" % pos2)

startwith() 檢測字符串是否以指定字符開頭 是返回true

endwith() 檢測是否已指定字符結束 不是返回 false

s = "__abcdefg%%"
    if s.startswith("__"):
        print("%s是以'__'開始的!" %s)
    else:
        print("不是!")

    if s.endswith("%%"):
        print("是!")
    else:
        print("不是")

replace() 字符替換 生成新的字符串

將ab替換爲666 替換前2個
s1 = "abcdab123abppqabdd"
    s2 = s1.replace("ab", "666", 2) 
    print(s2)

lstrip()rstrip() 刪除左側右側字符

    s = "  abc  "
    # 去除兩側空格
    s2 =  s.strip()
    # 去除左側空格
    s2 = s.lstrip()
    # 去除右側空格
    s2 = s.rstrip()
    print(s)
    print(s2)

center() ljust() rjust() 在指定長度空間中 居中 左對齊 右對齊

    s = "abc"
    #s2 = s.center(30, '#')
    #s2 = s.ljust(30, '#')
    s2 = s.rjust(30, '#')
    print(s2)

capitalize() 字符串首字母大寫

    s = "aaa bbb ccc dd"
    # 整個字符串首字母大寫
    s2 = s.capitalize()
    # 每個單詞首字母大寫
    s3 = s.title()
    # 整個字符串大寫
    s4 = s.upper()
    # 整個字符串小寫
    s5 = s4.lower()

title() 讓所有單詞的開頭字母大寫

upper() 所有字母大寫

lower() 所有字母小寫

a = ‘as da sd’
B = a.title()

partition(str) 將字符串分成三部分 str前 str str後

s = "abcde666oplm"
s2 = s.partition("666")
print(s2)

isalpha() 檢測字符串都是否字母 是true 否 flash

s1 = "123456"
    if s1.isdigit():
        print("全部是數字!")
    else:
        print("不全是數字!")

count() 統計該字符在字符串中出現的次數

s = "ab111ab222ab333ab444"
    print(s.count("ab"))

isdigit() 檢測是否都是數字 是 true 否 flash

islnum() 檢測字符串是否字母和數字組成

ispace() 檢測是否全是空格

發佈了36 篇原創文章 · 獲贊 10 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章