搜尋
首頁後端開發Python教學31個必備的Python字串方法,建議收藏!

31個必備的Python字串方法,建議收藏!

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

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 hellon'.strip('n')
print(s)
#
#hello
s = 'n t hellon'.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()

Python3.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 = "stringmethods in python"
s2 = s.replace(' ', '-')
print(s2)
# string----methods-in-python
s = "stringmethods 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


以上是31個必備的Python字串方法,建議收藏!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:51CTO.COM。如有侵權,請聯絡admin@php.cn刪除
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具