


A complete collection of Python string manipulation methods
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti
