搜尋
首頁後端開發Python教學盤點Python字串常見的16種操作方法

一、常用運算

以字串

'lstr = 'welcome to Beijing Museumitcpps fdsfs'

為例, 介紹字元常見的操作。

find

#偵測 str 是否包含在 lstr中,如果是傳回開始的索引值,否則傳回-1。

語法:

lstr.find(str, start=0, end=len(lstr))

#範例:

##
lstr = 'welcome to Beijing Museumitcpps fdsfs'
print(lstr.find("Museum"))


print(lstr.find("dada"))

執行結果:

盤點Python字串常見的16種操作方法


# index

跟find()方法一樣,只不過如果str不在lstr中會回報一個例外。

文法:

lstr.index(str, start=0, end=len(lstr))

例:

lstr = 'welcome to Beijing Museumitcpps fdsfs'


print(lstr.index("dada"))

运行结果:

盤點Python字串常見的16種操作方法


count

返回 str在start和end之间 在 lstr里面出现的次数

语法:

lstr.count(str, start=0, end=len(lstr))

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.count("s"))

运行结果:

盤點Python字串常見的16種操作方法


replace

把 lstr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

1str.replace(str1, str2,  1str.count(str1))

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.replace("s", "ttennd"))

运行结果:

盤點Python字串常見的16種操作方法


split

以 str 为分隔符切片 lstr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

1str.split(str=" ", 2)

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.split("to", 5))

运行结果:

盤點Python字串常見的16種操作方法


capitalize

把字符串的第一个字符大写。

lstr.capitalize()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.capitalize())

运行结果:

盤點Python字串常見的16種操作方法


title

把字符串的每个单词首字母大写。

>>> a = "hello itcast"
>>> a.title()
'Hello Itcast' #运行结果

startswith

检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False

1str.startswith(obj)

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.startswith('we'))

运行结果:

盤點Python字串常見的16種操作方法


endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.

1str.endswith(obj)

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.endswith('hfs'))

运行结果:

盤點Python字串常見的16種操作方法


lower

转换 lstr 中所有大写字符为小写

1str.lower()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.lower())

运行结果:

盤點Python字串常見的16種操作方法


upper

转换 lstr 中的小写字母为大写

1str.upper()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.upper())

运行结果:

盤點Python字串常見的16種操作方法


strip

删除lstr字符串两端的空白字符。

>>> a = "\n\t itcast \t\n"
>>> a.strip()
'itcast'  #运行结果

rfind

类似于 find()函数,不过是从右边开始查找。

1str.rfind(str, start=0,end=len(1str) )

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'
print(lstr.rfind('eijing'))

运行结果:

盤點Python字串常見的16種操作方法


rindex

类似于 index(),不过是从右边开始。

1str.rindex( str, start=0,end=len(1str))

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'
print(lstr.rindex('eijing'))

运行结果:

盤點Python字串常見的16種操作方法


partition

把lstr以str分割成三部分,str前,str和str后。

1str.partition(str)

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'
print(lstr.partition('eijing'))

运行结果:

盤點Python字串常見的16種操作方法


join

mystr 中每个字符后面插入str,构造出一个新的字符串。

lstr = 'welcome to Beijing Museumitcpps  fdsfs'
str='233'
lstr.join(str)
li=["my","name","is","LY"]
print(str.join(li))
运行结果:

盤點Python字串常見的16種操作方法


二、总结

本文详细的讲解了Python基础 ( 字符串 )。介绍了有关字符串,切片的操作。下标索引。以及在实际操作中会遇到的问题,提供了解决方案。希望可以帮助你更好的学习Python。

以上是盤點Python字串常見的16種操作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:Go语言进阶学习。如有侵權,請聯絡admin@php.cn刪除
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的內存足跡與python數組的內存足跡相比如何?列表的內存足跡與python數組的內存足跡相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

部署可執行的Python腳本時,如何處理特定環境的配置?部署可執行的Python腳本時,如何處理特定環境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

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

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

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

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

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1

記事本++7.3.1

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境