SoFunction
Updated on 2024-10-29

Python String Manipulation Methods

1. Remove spaces and special symbols

Copy Code The code is as follows.
().lstrip().rstrip(',')

2、Copy the string
Copy Code The code is as follows.
#strcpy(sStr1,sStr2)
sStr1 = 'strcpy'
sStr2 = sStr1
sStr1 = 'strcpy2'
print sStr2

3. Connecting strings
Copy Code The code is as follows.
#strcat(sStr1,sStr2)
sStr1 = 'strcat'
sStr2 = 'append'
sStr1 += sStr2
print sStr1

4. Finding Characters
Copy Code The code is as follows.
#strchr(sStr1,sStr2)
# < 0 for not found
sStr1 = 'strchr'
sStr2 = 's'
nPos = (sStr2)
print nPos

5. Compare strings
Copy Code The code is as follows.
#strcmp(sStr1,sStr2)
sStr1 = 'strchr'
sStr2 = 'strch'
print cmp(sStr1,sStr2)

6, scanning the string to see if it contains the specified characters
Copy Code The code is 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 Code The code is as follows.
#strlen(sStr1)
sStr1 = 'strlen'
print len(sStr1)

8, the string in the case conversion
Copy Code The code is as follows.
() # Lowercase
() #Capitalization
() #Case swaps
() # Initial capitalization
(S) # This is the method in the module. It separates the S's with the split() function, then capitalizes the first letter with capitalize(), and finally merges them together with join()
# Example:
#strlwr(sStr1)
sStr1 = 'JCstrlwr'
sStr1 = ()
#sStr1 = ()
print sStr1


9, append the specified length of the string
Copy Code The code is as follows.
#strncat(sStr1,sStr2,n)
sStr1 = '12345'
sStr2 = 'abcdef'
n = 3
sStr1 += sStr2[0:n]
print sStr1

10, string specified length comparison
Copy Code The code is as follows.
#strncmp(sStr1,sStr2,n)
sStr1 = '12345'
sStr2 = '123bc'
n = 3
print cmp(sStr1[0:n],sStr2[0:n])

11, copy the specified length of characters
Copy Code The code is as follows.
#strncpy(sStr1,sStr2,n)
sStr1 = ''
sStr2 = '12345'
n = 3
sStr1 = sStr2[0:n]
print sStr1

12, the first n characters of the string to replace the specified characters
Copy Code The code is as follows.
#strnset(sStr1,ch,n)
sStr1 = '12345'
ch = 'r'
n = 3
sStr1 = n * ch + sStr1[3:]
print sStr1

13. Scanning strings
Copy Code The code is as follows.
#strpbrk(sStr1,sStr2)
sStr1 = 'cekjgdklab'
sStr2 = 'gka'
nPos = -1
for c in sStr1:
    if c in sStr2:
        nPos = (c)
        break
print nPos

14、Flip the string
Copy Code The code is as follows.
#strrev(sStr1)
sStr1 = 'abcdefg'
sStr1 = sStr1[::-1]
print sStr1

15、Find String
Copy Code The code is as follows.
#strstr(sStr1,sStr2)
sStr1 = 'abcdefg'
sStr2 = 'cde'
print (sStr2)

16、Split String
Copy Code The code is as follows.
#strtok(sStr1,sStr2)
sStr1 = 'ab,cde,fgh,ijk'
sStr2 = ','
sStr1 = sStr1[(sStr2) + 1:]
print sStr1
# or
s = 'ab,cde,fgh,ijk'
print((','))

17. Connecting strings
Copy Code The code is as follows.
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print (mylist)

18. PHP addslashes implementation
Copy Code The code is as follows.
def addslashes(s):
    d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
    return ''.join((c, c) for c in s)

s = "John 'Johny' Doe (. \"Super Joe\")\\\0"
print s
print addslashes(s)

19. Display only letters and numbers
Copy Code The code is as follows.
def OnlyCharNum(s,oth=''):
    s2 = ();
    fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
    for c in s2:
        if not c in fomart:
            s = (c,'');
    return s;

print(OnlyStr("a000 aa-b"))

20. Intercepting strings
Copy Code The code is as follows.
str = '0123456789′
print str[0:3] #Intercept the first to the third character
print str[:] #Intercept all characters of the string
print str[6:] #Intercept the seventh character to the end
print str[:-3] #Intercept from the beginning until the penultimate third character
print str[2] #Intercept the third character
print str[-1] #Intercept the penultimate character
print str[::-1] #Create a string in the reverse order of the original string
print str[-3:-1] #Intercept the characters before the penultimate digit and the first digit.
print str[-3:] #Intercepts the penultimate digit to the end
print str[:-5:-3] #Intercept in reverse order, what does that mean?

21. Alignment of strings in the output
Copy Code The code is as follows.
(width,[fillchar])
# Output width characters, S left-justified, shortfall filled with fillchar, default is space.
(width,[fillchar]) #right-aligned
(width, [fillchar]) #center alignment
(width) #Turn S into width long and right-aligned, with the shortfall made up with zeros

22. Search and replace in strings
Copy Code The code is as follows.
(substr, [start, [end]])
# Returns the label of the first letter in S where substr occurs, or -1 if there is no substr in S. start and end are equivalent to searching in S[start:end].
(substr, [start, [end]])
# Same as find(), except that it returns a runtime error if there is no substr in S
(substr, [start, [end]])
# Returns the first letter of the last occurrence of substr in S, or -1 if there is no substr in S, i.e. the first letter of the first occurrence of substr counting from the right.
(substr, [start, [end]])
(substr, [start, [end]]) #count the number of times substr appears in S
(oldstr, newstr, [count])
# Replace oldstar in S with newstr, count is the number of replacements. This is the general form of replacement, there are some functions for special character replacement
([chars])
# Remove all the characters in the chars before and after S. This can be interpreted as replacing the chars before and after S with None.
([chars])
([chars])
([tabsize])
# Replace tab characters in S with no spaces, each tab is replaced with tabsize spaces, default is 8.

23. String splitting and combining
Copy Code The code is as follows.
([sep, [maxsplit]])
# Split S into a list using sep as the separator. maxsplit indicates the number of splits. The default splitter is a blank character
([sep, [maxsplit]])
([keepends])
# Divide S into a list according to line separators. depends is a bool value, if true after each line while the line separators will be preserved.
(seq) #join the sequence represented by seq, a sequence of strings, with S

24, string mapping, this function contains two functions
Copy Code The code is as follows.
(from, to)
# Returns a translation table of 256 characters, where the characters in from are converted to to one-to-one, so from and to must be of equal length.
(table[,deletechars])
# Use the above function to produce a translation table to translate S and delete the characters in deletechars. Note that if S is a unicode string, then the deletechars argument is not supported, and the same function can be achieved by translating a character to None. You can also use the codecs module to create more powerful translation tables.

25, the string also has a pair of encoding and decoding functions
Copy Code The code is as follows.
([encoding,[errors]])
# where encoding can have various values, such as gb2312 gbk gb18030 bz2 zlib big5 bzse64 etc. are supported. errors defaults to 'strict', meaning UnicodeError. possible values include 'ignore', 'replace', ' xmlcharrefreplace', 'backslashreplace' and all the values registered with codecs.register_error. This part is related to the codecs module and is not well understood.
([encoding,[errors]])

26, string test, judgment function, this type of function is not in the string module, these functions return a bool value
Copy Code The code is as follows.
(prefix[,start[,end]])
# Does it start with prefix
(suffix[,start[,end]])
#Ending in suffix
()
# Is it all letters and numbers with at least one character
() # Is it all letters and at least one character
() # Is it all numbers and at least one character
() # Is it all whitespace with at least one character
() # Are all the letters in S lowercase?
() # Are the letters in S capitalized?
() # whether S is initial capitalized or not

27, string type conversion function, these functions are only in the string module has
Copy Code The code is as follows.
(s[,base])
#base defaults to 10, if it is 0, then s can be 012 or 0x23 this form of the string, if it is 16 then s can only be 0x23 or 0X12 this form of the string
(s[,base]) # to long
(s[,base]) #convert to float

Here again, the string object is immutable, which means that after python creates a string, you can't change a part of that character. Any function above that changes the string will return a new string, the original string is not changed. There is actually a workaround for this, you can use the function S=list(S) to change S into a list with a single character as a member, in which case you can change the value by using S[3]='a' and then restore it to a string using S=" ".join(S)