摘要:盤點 Python 中字元串的幾個常用操作,對新手極度的友好。 本文分享自華為雲社區《盤點 Python 中字元串的常用操作,對新手極度友好》,作者:TT-千葉 。 在 Python 中字元串的表達方式有四種 一對單引號一對雙引號一對三個單引號一對三個雙引號a = ‘abc’b= “abc”c ...
摘要:盤點 Python 中字元串的幾個常用操作,對新手極度的友好。
本文分享自華為雲社區《盤點 Python 中字元串的常用操作,對新手極度友好》,作者:TT-千葉 。
在 Python 中字元串的表達方式有四種
一對單引號
一對雙引號
一對三個單引號
一對三個雙引號
a = ‘abc’
b= “abc”
c = ‘’‘abc’’’
d = “”“abc”""
print(type(a)) # <class ‘str’>
print(type(b)) # <class ‘str’>
print(type©) # <class ‘str’>
print(type(d)) # <class ‘str’>
單雙引號混合使用
a = “LiMing say ‘nice to meet you’”
同樣也可以通過轉義的方式不用在裡面寫雙引號
a = “LiMing say “nice to meet you””
print(a)
總結就是需要外面用了雙引號,裡面需要引用的語句可以用單引號括起來,反之亦然。
通常情況根據個人喜好,基本都是使用單引號或者雙引號。有些特殊情況,比如需要表示多行時,可以選擇三個單(雙)引號,並且無序用 \ 進行轉移,可直接使用單引號和雙引號。
a = ‘’’
My Name is 阿亮,
Let’s say ‘Hello’
‘’’
print(a)
字元串的下標和切換
下標:字元串是一個個字元拼接而成,下標可以理解為每個字元的編號,從 0 開始依次類推。
作用:通過下標去操作字元串中的元素
H的下標為0, e的下標為1 …依次類推
a = ‘HelloWorld’
獲取字元串a中下標為4的元素
print(a[4]) # o 下標為4的元素為o
修改字元串中的元素是不是可以直接賦值呢? 例如:
a = ‘HelloWorld’
a[4] = ‘k’
print(a)
上面的代碼運行之後發現報錯。
TypeError: ‘str’ object does not support item assignment
原因是因為: 字元串一旦創建之後,裡面的元素是不可以修改的。
所以字元串是無法直接進行修改的。
字元串運算
字元串運算中用到了 + 、*、>、<、!= 、= 等邏輯運算符。
字元串的相加操作,也可以理解為拼接操作。例如:
a = ‘Hello’ + ’ World’
print(a) # Hello World
也可以寫成
a = ‘Hello’ ’ World’
print(a) # Hello World
字元串的乘法操作,可以理解為克隆操作,字元串只能與整數(n)想乘,代表克隆 n 個字元串。
a = ‘a’
print(a * 2) # aa
b = ‘-’
print(b * 10) # ----------
切片
字元串的切片也稱為字元串截取。 所有操作都是通過字元串的下標進行操作的。
用法:字元串 [開始索引(start):結束索引(end):步長(step)(預設 1)]
步長(step):每隔(step-1)個取一個元素,當 step 為負數時,代表從右向左取元素,
a = ‘abcdefghijklmn’
從下標1開始 到4結束 進行切片 (包括1,不包括4,即左開又閉)
print(a[1:4]) # bcd
print(a[1:8]) # bcdefgh
print(a[1:8:2])# 步長為2, 結果:bdfh
當補償為負數時,代表逆向截取。 初始從坐標8開始,每隔一個元素取一個值,到下標為1時結束
print(a[8:1:-2]) # igec
字元串的常用操作
這裡以代碼 + 註釋的方式,展示幾個常用的字元串操作。
a = ’ Hello World ’
獲取字元串的長度
print(len(a)) # 13
刪除字元串兩邊的空格
print(a.strip()) # Hello World
刪除左邊的空格
print(a.lstrip()) # Hello World (只刪除左邊的空格)
刪除字元串右邊的空格
print(a.rstrip()) # Hello World
通過指定連接符 鏈接字元串
lst = [‘LiMing’, ‘Tom’]
print(’***’.join(lst)) # LiMing***Tom
首字母大寫
m = ‘hello world’
print(m.capitalize()) # Hello world
返回標題化字元串,即每個單詞首字母大寫
print(m.title()) # Hello World
列印輸出字元,將字元串放在中間,
center(width, fillchar) width: 字元串的總長度, fillchar:填充字元
print(a.center(20, ‘*’)) # *** Hello World ****
是否以xxx開頭
n = ‘Hello’
print(n.startswith(‘H’)) # True
是否以xxx結尾
print(n.endswith(‘o’)) # True
字元串是全純英文字元
print(a.isalpha()) # False , 因為字元串a中 ’ Hello World ’ 有空格,因此返回False
print(‘HelloWorld’.isalpha()) #True
判斷字元串中是否全部為數字或者英文
print(‘Hello2World’.isalnum()) # True
print(‘123’.isalnum()) # True
print(‘abc&11’.isalnum()) # False
判斷是否為整數
print(‘123’.isdigit()) # True
print(‘1.23’.isdigit()) # False
判斷字元是否全為小寫
print(‘abc’.islower()) # True
判斷字元是否全為大寫
print(‘Abc’.isupper()) # False
print(‘ABC’.isupper()) # True
字元串小寫轉大寫
print(‘abc’.upper()) # ABC
字元串大寫轉小寫
print(‘ABC’.lower()) # abc
字元串的替換
b = ‘aabbcc’.replace(‘a’, ‘m’)
print(b) # mmbbcc
1 代表替換的個數
b = ‘aabbcc’.replace(‘a’, ‘m’, 1)
print(b) # mabbcc
split 字元串切割,預設空格切割
print(‘aa bb cc’.split()) # [‘aa’, ‘bb’, ‘cc’]
print(‘ab,cd,ef’.split(’,’)) # [‘ab’, ‘cd’, ‘ef’]
字元串換行分割
a = “”"
My Name is ‘762459510,
歡迎添加
“”"
print(a.splitlines()) # [’’, " My Name is ‘762459510’,", ’ 歡迎添加’, ’ ']
字元串的查找
字元串查找常用的方法用 index、find
兩者功能相似,區別在於 find 查找不到元素時返回 -1, 不會影響程式運行,而 index 則會拋出異常。
a = ‘abcdef’
查找到元素返回對應的下標
print(a.find(‘c’)) # 2
print(a.find(‘h’)) # -1
print(a.index(‘c’)) # 2
print(a.index(‘h’)) # 拋出異常,ValueError: substring not found
rfind: 類似於 find () 函數,不過是從右邊開始查找;返回字元串最後一次出現的位置,如果沒有匹配項則返回 - 1 。rindex 同理
a = ‘acmncd’
從右邊開始計算,返回第一個匹配到的下標
print(a.rfind(‘c’)) # 4
print(a.rindex(‘c’)) # 4
字元串的格式化
name = ‘762459510’
%s 用於輸出字元串
print(‘我的月球號是: %s’ % name)
age = 18
%d 用於輸出十進位數字
print(‘我的年齡是:%d’ % age)
money = 1.23
%f 浮點數,預設顯示小數點後6位
print(‘我身上有:%f 元’ % money )
指定小數點後的位數
print(‘我身上有:%.2f 元’ % money )
format 操作
除了使用 % 進行格式化,也可以使用 format
print(’{} {}’.format(‘Hello’, ‘World’)) # Hello World
print(’{0} {1}’.format(‘Hello’, ‘World’)) # Hello World
print(’{1}, {0}, {1}’.format(‘A’, ‘B’)) #B, A, B
print(‘今年是 {}年.’.format(2022)) # 今年是 2022年.