當前位置: 妍妍網 > 辦公

例項講解31個Python字串方法

2024-06-05辦公

字串是Python中基本的數據型別,幾乎在每個Python程式中都會使用到它。

今天就帶大家學習一下31個常用的內建字串方法。

希望大家能從中找到對自己有幫助的技巧。

▍1、Slicing

slicing切片,按照一定條件從列表或者元組中取出部份元素(比如特定範圍、索引、分割值)

s = ' hello '
s = s[:]
print(s)
# hello

s = ' hello '
s = s[3:8]
print(s)
# hello

▍2、 strip()

strip()方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列。

s = ' hello '.strip()
print(s)
# hello

s = '###hello###'.strip()
print(s)
# ###hello###

在使用strip()方法時,預設去除空格或換行符,所以#號並沒有去除。

可以給strip()方法添加指定字元,如下所示。

s = '###hello###'.strip('#')
print(s)
# hello

此外當指定內容不在頭尾處時,並不會被去除。

s = ' \n \t hello\n'.strip('\n')
print(s)
#
# hello

s = '\n \t hello\n'.strip('\n')
print(s)
# hello

第一個\n前有個空格,所以只會去取尾部的換行符。

最後strip()方法的參數是剝離其值的所有組合,這個可以看下面這個案例。

s = 'www.baidu.com'.strip('cmow.')
print(s)
# baidu

最外層的首字元和尾字元參數值將從字串中剝離。字元從前端移除,直到到達一個不包含在字元集中的字串字元為止。

在尾部也會發生類似的動作。

▍3、 lstrip()

移除 字元 左側 指定的字元 (預設為空格或換行符)或字元序列。

s = ' hello '.lstrip()
print(s)
# hello

同樣的,可以移除左側所有包含在字元集中的字串。

s = 'Arthur: three!'.lstrip('Arthur: ')
print(s)
# ee!

▍4、rstrip()

移除字串右側指定的字元(預設為空格或換行符)或字元序列。

s = ' hello '.rstrip()
print(s)
# hello

▍5、 removeprefix()

Python3.9中移除字首的函式。

# python 3.9
s = 'Arthur: three!'.removeprefix('Arthur: ')
print(s)
# three!

和strip()相比,並不會把 集中的字串進行逐個匹配。

▍6、removesuffix()

P ython3.9中移除 字尾的函式

s = 'HelloPython'.removesuffix('Python')
print(s)
# Hello

▍7、 replace()

把字串中的內容替換成指定的內容。

s = 'string methods in python'.replace(' ''-')
print(s)
# string-methods-in-python

s = 'string methods in python'.replace(' ''')
print(s)
# stringmethodsinpython

▍8、 re.sub()

re是正則的運算式,sub是substitute表示替換。

re.sub則是相對復雜點的替換。

import re
s = "string methods in python"
s2 = s.replace(' ''-')
print(s2)
# string----methods-in-python

s = "string methods in python"
s2 = re.sub("\s+""-", s)
print(s2)
# string-methods-in-python

和replace()做對比,使用re.sub()進行替換操作,確實更高級點。

▍9、 split()

對字串做分隔處理,最終的結果是一個列表。

s = 'string methods in python'.split()
print(s)
# ['string', 'methods', 'in', 'python']

當不指定分隔符時,預設按空格分隔。

s = 'string methods in python'.split(',')
print(s)
# ['string methods in python']

此外,還可以指定字串的分隔次數。

s = 'string methods in python'.split(' ', maxsplit=1)
print(s)
# ['string', 'methods in python']

▍10、 rsplit()

從右側開始對字串進行分隔。

s = 'string methods in python'.rsplit(' ', maxsplit=1)
print(s)
# ['string methods in', 'python']

▍11、 join()

string.join(seq)。以string作為分隔符,將seq中所有的元素(的字串表示)合並為一個新的字串。

list_of_strings = ['string''methods''in''python']
s = '-'.join(list_of_strings)
print(s)
# string-methods-in-python

list_of_strings = ['string''methods''in''python']
s = ' '.join(list_of_strings)
print(s)
# string methods in python

▍12、 upper()

將字串中的字母,全部轉換為大寫。

s = 'simple is better than complex'.upper()
print(s)
# SIMPLE IS BETTER THAN COMPLEX

▍13、 lower()

將字串中的 字母,全部轉換為小寫。

s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()
print(s)
# simple is better than complex

▍14、capitalize()

將字串中的第一個 字母轉換為大寫。

s = 'simple is better than complex'.capitalize()
print(s)
# Simple is better than complex

▍15、 islower()

判斷 字串中的所有 字母是否都為小寫,是則返回True,否則返回False。

print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False
print('simple is better than complex'.islower()) # True

▍16、isupper()

判斷 字串中的所有 字母是否都為大寫,是則返回True,否則返回False。

print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True
print('SIMPLE IS BETTER THAN complex'.isupper()) # False

▍17、 isalpha()

如果字串至少有一個字元並且所有字元都是字母,則返回 True,否則返回 False。

s = 'python'
print(s.isalpha())
# True
s = '123'
print(s.isalpha())
# False
s = 'python123'
print(s.isalpha())
# False
s = 'python-123'
print(s.isalpha())
# False

▍18、isnumeric()

如果字串中只包含數位字元,則返回 True,否則返回 False。

s = 'python'
print(s.isnumeric())
# False
s = '123'
print(s.isnumeric())
# True
s = 'python123'
print(s.isnumeric())
# False
s = 'python-123'
print(s.isnumeric())
# False

▍19、isalnum()

如果字串中至少有一個字元並且所有字元都是字母或數位,則返回True,否則返回 False。

s = 'python'
print(s.isalnum())
# True
s = '123'
print(s.isalnum())
# True
s = 'python123'
print(s.isalnum())
# True
s = 'python-123'
print(s.isalnum())
# False

▍20、count()

返回指定內容在字串中出現的次數。

n = 'hello world'.count('o')
print(n)
# 2
n = 'hello world'.count('oo')
print(n)
# 0

▍21、 find()

檢測指定內容是否包含在字串中,如果是返回開始的索引值,否則返回-1。

s = 'Machine Learning'
idx = s.find('a')
print(idx)
print(s[idx:])
# 1
# achine Learning
s = 'Machine Learning'
idx = s.find('aa')
print(idx)
print(s[idx:])
# -1
# g

此外,還可以指定開始的範圍。

s = 'Machine Learning'
idx = s.find('a'2)
print(idx)
print(s[idx:])
# 10
# arning

▍22、rfind()

類似於find()函式,返回字串最後一次出現的位置,如果沒有匹配項則返回 -1。

s = 'Machine Learning'
idx = s.rfind('a')
print(idx)
print(s[idx:])
# 10
# arning

▍23、 startswith()

檢查字串是否是以指定內容開頭,是則返回 True,否則返回 False。

print('Patrick'.startswith('P'))
# True

▍24、 endswith()

檢查字串是否是以 指定內容 結束,是則返回 True,否則返回 False。

print('Patrick'.endswith('ck'))
# True

▍25、 partition()

string.partition(str),有點像find()和split()的結合體。

從str出現的第一個位置起,把字串string分成一個3 元素的元組(string_pre_str,str,string_post_str),如果string中不包含str則 string_pre_str==string。

s = 'Python is awesome!'
parts = s.partition('is')
print(parts)
# ('Python ', 'is', ' awesome!')
s = 'Python is awesome!'
parts = s.partition('was')
print(parts)
# ('Python is awesome!', '', '')

▍26、center()

返回一個原字串居中,並使用空格填充至長度width的新字串。

s = 'Python is awesome!'
s = s.center(30'-')
print(s)
# ------Python is awesome!------

▍27、ljust()

返回一個原字串左對齊,並使用空格填充至長度width的新字串。

s = 'Python is awesome!'
s = s.ljust(30'-')
print(s)
# Python is awesome!------------

▍28、rjust()

返回一個原字串右對齊,並使用空格填充至長度width的新字串。

s = 'Python is awesome!'
s = s.rjust(30'-')
print(s)
# ------------Python is awesome!

▍29、f-Strings

f-string是格式化字串的新語法。

與其他格式化方式相比,它們不僅更易讀,更簡潔,不易出錯,而且速度更快!

num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
print(s)
# Python is the number 1 in programming!

num = 1
language = 'Python'
s = f'{language} is the number {num*8} in programming!'
print(s)
# Python is the number 8 in programming!

▍30、swapcase()

翻轉字串中的字母大小寫。

s = 'HELLO world'
s = s.swapcase()
print(s)
# hello WORLD

▍31、zfill()

string.zfill(width)。

返回長度為width的字串,原字串string右對齊,前面填充0。

s = '42'.zfill(5)
print(s)
# 00042
s = '-42'.zfill(5)
print(s)
# -0042
s = '+42'.zfill(5)
print(s)
# +0042

Crossin的新書【 碼上行動:用ChatGPT學會Python編程 】已經上市了。 本書以ChatGPT為輔助,系統全面地講解了如何掌握Python編程,適合Python零基礎入門的讀者學習。

購買後可加入讀者交流群,Crossin為你開啟陪讀模式,解答你在閱讀本書時的一切疑問。

Crossin的其他書籍:

添加微信 crossin123 ,加入編程教室共同學習 ~

感謝 轉發 點贊 的各位~