Home Backend Development Python Tutorial A complete collection of Python string manipulation methods

A complete collection of Python string manipulation methods

Dec 07, 2016 am 09:30 AM

A large collection of Python string operation methods, including almost all commonly used Python string operations, such as string replacement, deletion, interception, copy, connection, comparison, search, split, etc. Friends who need it can refer to it


1. Remove spaces and special symbols


Copy the code as follows:

s.strip().lstrip().rstrip(',')

2. Copy the string

Copy the code as follows:

#strcpy(sStr1,sStr2)
sStr1 = 'strcpy'
sStr2 = sStr1
sStr1 = 'strcpy2'
print sStr2

3. Connection string

Copy the code as follows:

#strcat(sStr1,sStr2)
sStr1 = 'strcat'
sStr2 = 'append'
sStr1 += sStr2
print sStr1

4. Find the character

Copy the code as follows:

#strchr(sStr1,sStr2)
# < 0 means not found
sStr1 = 'strchr'
sStr2 = 's'
nPos = sStr1.index(sStr2)
print nPos

5. Compare strings

Copy the code as follows:

#strcmp(sStr1,sStr2)
sStr1 = ' strchr'
sStr2 = 'strch'
print cmp(sStr1,sStr2)

6. Scan whether the string contains the specified characters

Copy the code as follows:

#strspn(sStr1,sStr2)
sStr1 = '12345678'
sStr2 = '456'
#sStr1 and chars both in sStr1 and sStr2
print len(sStr1 and sStr2)

7. String length

Copy the code as follows:

#strlen(sStr1)
sStr1 = 'strlen '
print len(sStr1)

8. Convert the case in the string

Copy the code as follows:

S.lower() #lowercase
S.upper() #uppercase
S.swapcase() # Case swap
S.capitalize() #Capitalize the first letter
String.capwords(S) #This is a method in the module. It separates S using the split() function, then uses capitalize() to capitalize the first letter, and finally uses join() to merge them together
#Example:
#strlwr(sStr1)
sStr1 = 'JCstrlwr'
sStr1 = sStr1 .upper()
#sStr1 = sStr1.lower()
print sStr1


9. Append a string of specified length

Copy the code as follows:

#strncat(sStr1,sStr2,n)
sStr1 = '12345 '
sStr2 = 'abcdef'
n = 3
sStr1 += sStr2[0:n]
print sStr1

10. String specified length comparison

Copy the code as follows:

#strncmp(sStr1,sStr2,n )
sStr1 = '12345'
sStr2 = '123bc'
n = 3
print cmp(sStr1[0:n],sStr2[0:n])

11. Copy characters of the specified length

Copy code The code is as follows :

#strncpy(sStr1,sStr2,n)
sStr1 = ''
sStr2 = '12345'
n = 3
sStr1 = sStr2[0:n]
print sStr1

12. Change the first n characters of the string Replace with the specified characters

Copy the code as follows:

#strnset(sStr1,ch,n)
sStr1 = '12345'
ch = 'r'
n = 3
sStr1 = n * ch + sStr1[3: ]
print sStr1

13. Scan the string

Copy the code as follows:

#strpbrk(sStr1,sStr2)
sStr1 = 'cekjgdklab'
sStr2 = 'gka'
nPos = -1
for c in sStr1:
if c in sStr2: nPos = sStr1.index(c)
print nPos

14. Flip the string

Copy the code as follows:

#strrev(sStr1)
sStr1 = 'abcdefg '
sStr1 = sStr1[::-1]
print sStr1

15. Find the string

Copy the code. The code is as follows:

#strstr(sStr1,sStr2)
sStr1 = 'abcdefg'
sStr2 = 'cde'
print sStr1.find (sStr2)

16. Split the string

Copy the code as follows:

#strtok(sStr1,sStr2)
sStr1 = 'ab,cde,fgh,ijk'
sStr2 = ','
sStr1 = sStr1[sStr1 .find(sStr2) + 1:]
print sStr1
#or
s = 'ab,cde,fgh,ijk'
print(s.split(','))

17. Connection string

Copy code The code is as follows:

delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)

18. Implementation of addslashes in PHP

Copy The code is as follows:

def addslashes(s):
d = {'"':'\"', "'":"\'", "# The encoding can have multiple values, such as gb2312 gbk gb18030 bz2 zlib big5 bzse64, etc. are supported. The default value of errors is "strict", which means UnicodeError. Possible values ​​are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and all values ​​registered via codecs.register_error. This part of the content involves the codecs module, which is not very clear
S.decode([encoding,[errors]])

26. String testing and judgment functions. This type of function does not exist in the string module. These functions return It is a bool value

Copy the code as follows:

S.startswith(prefix[,start[,end]])
#Whether it starts with prefix
S.endswith(suffix[,start[,end]])
#With The end of suffix
S.isalnum()
#Is it all letters and numbers, and at least one character?
S.isalpha() #Is it all letters, and at least one character?
S.isdigit() #Is it all numbers? , and have at least one character
S.isspace() #Whether they are all blank characters, and have at least one character
S.islower() #Whether the letters in S are all lowercase
S.isupper() #The letters in S Is it capitalized
S.istitle() #Is S the first letter capitalized?

27. String type conversion functions, these functions are only available in the string module

Copy the code as follows:

string.atoi (s[,base])
#base defaults to 10. If it is 0, then s can be a string in the form of 012 or 0x23. If it is 16, then s can only be a character in the form of 0x23 or 0X12. String
string.atol(s[,base]) #Convert to long
string.atof(s[,base]) #Convert to float


I emphasize again that string objects are immutable, that is to say After creating a string in python, you cannot change a certain part of the characters. After any of the above functions changes the string, it will return a new string, and the original string has not changed. In fact, there is a workaround for this. You can use the S=list(S) function to turn S into a list with a single character as a member. In this case, you can use S[3]='a' to change the value, and then Then use S=" ".join(S) to restore it to a string

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Scientific Computing: A Detailed Look Python for Scientific Computing: A Detailed Look Apr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles