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

Implementing factory pattern in Python can create different types of objects by creating a unified interface. The specific steps are as follows: 1. Define a basic class and multiple inheritance classes, such as Vehicle, Car, Plane and Train. 2. Create a factory class VehicleFactory and use the create_vehicle method to return the corresponding object instance according to the type parameter. 3. Instantiate the object through the factory class, such as my_car=factory.create_vehicle("car","Tesla"). This pattern improves the scalability and maintainability of the code, but it needs to be paid attention to its complexity

In Python, the r or R prefix is used to define the original string, ignoring all escaped characters, and letting the string be interpreted literally. 1) Applicable to deal with regular expressions and file paths to avoid misunderstandings of escape characters. 2) Not applicable to cases where escaped characters need to be preserved, such as line breaks. Careful checking is required when using it to prevent unexpected output.

In Python, the __del__ method is an object's destructor, used to clean up resources. 1) Uncertain execution time: Relying on the garbage collection mechanism. 2) Circular reference: It may cause the call to be unable to be promptly and handled using the weakref module. 3) Exception handling: Exception thrown in __del__ may be ignored and captured using the try-except block. 4) Best practices for resource management: It is recommended to use with statements and context managers to manage resources.

The pop() function is used in Python to remove elements from a list and return a specified position. 1) When the index is not specified, pop() removes and returns the last element of the list by default. 2) When specifying an index, pop() removes and returns the element at the index position. 3) Pay attention to index errors, performance issues, alternative methods and list variability when using it.

Python mainly uses two major libraries Pillow and OpenCV for image processing. Pillow is suitable for simple image processing, such as adding watermarks, and the code is simple and easy to use; OpenCV is suitable for complex image processing and computer vision, such as edge detection, with superior performance but attention to memory management is required.

Implementing PCA in Python can be done by writing code manually or using the scikit-learn library. Manually implementing PCA includes the following steps: 1) centralize the data, 2) calculate the covariance matrix, 3) calculate the eigenvalues and eigenvectors, 4) sort and select principal components, and 5) project the data to the new space. Manual implementation helps to understand the algorithm in depth, but scikit-learn provides more convenient features.

Calculating logarithms in Python is a very simple but interesting thing. Let's start with the most basic question: How to calculate logarithm in Python? Basic method of calculating logarithm in Python The math module of Python provides functions for calculating logarithm. Let's take a simple example: importmath# calculates the natural logarithm (base is e) x=10natural_log=math.log(x)print(f"natural log({x})={natural_log}")# calculates the logarithm with base 10 log_base_10=math.log10(x)pri

To implement linear regression in Python, we can start from multiple perspectives. This is not just a simple function call, but involves a comprehensive application of statistics, mathematical optimization and machine learning. Let's dive into this process in depth. The most common way to implement linear regression in Python is to use the scikit-learn library, which provides easy and efficient tools. However, if we want to have a deeper understanding of the principles and implementation details of linear regression, we can also write our own linear regression algorithm from scratch. The linear regression implementation of scikit-learn uses scikit-learn to encapsulate the implementation of linear regression, allowing us to easily model and predict. Here is a use sc


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

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
