摘要:盤點 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年.
點擊關注,第一時間了解華為云新鮮技術~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540719.html
標籤:其他
