search
HomeBackend DevelopmentPython TutorialInventory of 16 common operations methods on Python strings

1. Common operations

Take the string

'lstr = 'welcome to Beijing Museumitcpps fdsfs'

as an example, Introduces common operations on characters.

find

Check whether str is included in lstr, if so, return the starting index value, otherwise return -1.

Grammar:

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

Example:

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


print(lstr.find("dada"))

operation result:

Inventory of 16 common operations methods on Python strings


index

The same as the find() method, except that if str is not in lstr, an exception will be reported.

grammar:

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

例:

lstr = 'welcome to Beijing Museumitcpps fdsfs'


print(lstr.index("dada"))

运行结果:

Inventory of 16 common operations methods on Python strings


count

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

语法:

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

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.count("s"))

运行结果:

Inventory of 16 common operations methods on Python strings


replace

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

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

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


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

运行结果:

Inventory of 16 common operations methods on Python strings


split

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

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

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


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

运行结果:

Inventory of 16 common operations methods on Python strings


capitalize

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

lstr.capitalize()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.capitalize())

运行结果:

Inventory of 16 common operations methods on Python strings


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'))

运行结果:

Inventory of 16 common operations methods on Python strings


endswith

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

1str.endswith(obj)

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.endswith('hfs'))

运行结果:

Inventory of 16 common operations methods on Python strings


lower

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

1str.lower()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.lower())

运行结果:

Inventory of 16 common operations methods on Python strings


upper

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

1str.upper()

例:

lstr = 'welcome to Beijing Museumitcpps  fdsfs'


print(lstr.upper())

运行结果:

Inventory of 16 common operations methods on Python strings


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'))

运行结果:

Inventory of 16 common operations methods on Python strings


rindex

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

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

例:

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

运行结果:

Inventory of 16 common operations methods on Python strings


partition

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

1str.partition(str)

例:

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

运行结果:

Inventory of 16 common operations methods on Python strings


join

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

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

Inventory of 16 common operations methods on Python strings


二、总结

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

The above is the detailed content of Inventory of 16 common operations methods on Python strings. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

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

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools