Python string manipulation methods

  • 2020-04-02 13:28:17
  • OfStack

1. Remove Spaces and special symbols

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

2. Copy the string
#strcpy(sStr1,sStr2)
sStr1 = 'strcpy'
sStr2 = sStr1
sStr1 = 'strcpy2'
print sStr2

3. Concatenate strings
#strcat(sStr1,sStr2)
sStr1 = 'strcat'
sStr2 = 'append'
sStr1 += sStr2
print sStr1

4. Find characters
#strchr(sStr1,sStr2)
# < 0  For was not found 
sStr1 = 'strchr'
sStr2 = 's'
nPos = sStr1.index(sStr2)
print nPos

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

6, scan the string for the specified characters
#strspn(sStr1,sStr2)
sStr1 = '12345678'
sStr2 = '456'
#sStr1 and chars both in sStr1 and sStr2
print len(sStr1 and sStr2)

7. String length
#strlen(sStr1)
sStr1 = 'strlen'
print len(sStr1)

Converts case to case in a string
S.lower() # lowercase  
S.upper() # A capital  
S.swapcase() # Case interchange  
S.capitalize() # Capital letter  
String.capwords(S) # This is the method in the module. It is the S with split() The function is separated and then used capitalize() Capitalize the first letter and use it at the end join() Merge together  
# Example: 
#strlwr(sStr1)
sStr1 = 'JCstrlwr'
sStr1 = sStr1.upper()
#sStr1 = sStr1.lower()
print sStr1

Appends a string of the specified length
#strncat(sStr1,sStr2,n)
sStr1 = '12345'
sStr2 = 'abcdef'
n = 3
sStr1 += sStr2[0:n]
print sStr1

10. String specifies length comparison
#strncmp(sStr1,sStr2,n)
sStr1 = '12345'
sStr2 = '123bc'
n = 3
print cmp(sStr1[0:n],sStr2[0:n])

11. Copies a character of the specified length
#strncpy(sStr1,sStr2,n)
sStr1 = ''
sStr2 = '12345'
n = 3
sStr1 = sStr2[0:n]
print sStr1

Replaces the first n characters of a string with the specified character
#strnset(sStr1,ch,n)
sStr1 = '12345'
ch = 'r'
n = 3
sStr1 = n * ch + sStr1[3:]
print sStr1

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

14. Flip the string
#strrev(sStr1)
sStr1 = 'abcdefg'
sStr1 = sStr1[::-1]
print sStr1

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

16. Split the string
#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(','))

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

18. Implementation of addslashes in PHP
def addslashes(s):
    d = {'"':'\"', "'":"\'", "0":"\0", "\":"\\"}
    return ''.join(d.get(c, c) for c in s)

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

19. Display only letters and Numbers
def OnlyCharNum(s,oth=''):
    s2 = s.lower();
    fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
    for c in s2:
        if not c in fomart:
            s = s.replace(c,'');
    return s;

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

20. Intercepts strings
str = '0123456789 ' 
print str[0:3] # Intercepts the first to the third character 
print str[:] # Intercepts all characters of a string 
print str[6:] # Intercepts the seventh character to the end 
print str[:-3] # Intercept from scratch until the third to last character 
print str[2] # Intercepts the third character 
print str[-1] # Intercepts the reciprocal first character 
print str[::-1] # Creates a string in the opposite order of the original string 
print str[-3:-1] # Intercepts the character before the last and last digit 
print str[-3:] # Cut the last but one digit to the end 
print str[:-5:-3] # Reverse interception, what exactly does it mean? 

21. String alignment on output
S.ljust(width,[fillchar]) 
# The output width A character, S Left - aligned, use less fillchar Fill, default is space.  
S.rjust(width,[fillchar]) # Align right  
S.center(width, [fillchar]) # In the middle of alignment,  
S.zfill(width) # the S become width Long, and aligned to the right, less than the part used 0 Make up 

Search and replace in strings
S.find(substr, [start, [end]]) 
# return S Appear in the substr The first letter of the label if S There is no substr It returns -1 . start and end The action is the same as in S[start:end] In the search  
S.index(substr, [start, [end]]) 
# with find() Same, just in S There is no substr , a runtime error is returned  
S.rfind(substr, [start, [end]]) 
# return S The last to appear in substr The first letter of the label if S There is no substr It returns -1 That is to say the first time from the right substr The first letter of the label  
S.rindex(substr, [start, [end]]) 
S.count(substr, [start, [end]]) # To calculate substr in S Is the number of times  
S.replace(oldstr, newstr, [count]) 
# the S In the oldstar Replace with newstr . count Is the number of substitutions. This is the general form of substitution, and there are some functions that do special character substitution  
S.strip([chars]) 
# the S In the front and back chars All the characters are removed, can be understood as to put S Before and after chars Replace with None 
S.lstrip([chars]) 
S.rstrip([chars]) 
S.expandtabs([tabsize]) 
# the S In the tab Character substitution no Spaces, each tab Replace with tabsize Space, by default 8 a 

23. Segmentation and combination of strings
S.split([sep, [maxsplit]]) 
# In order to sep For the separator, put S Divided into a list . maxsplit Represents the number of partitions. The default separator is a blank character  
S.rsplit([sep, [maxsplit]]) 
S.splitlines([keepends]) 
# the S Divide into one by line separator list . keepends Is a bool If true, the line separator is reserved after each line.  
S.join(seq) # the seq Represents a sequence -- a sequence of strings S connect 

24. String mapping. This feature contains two functions
String.maketrans(from, to) 
# Returns a 256 A translation table of characters, in which from Are converted to one by one to , so from and to It has to be the same length.  
S.translate(table[,deletechars]) 
#  Use the above function to post the translation table, put S Translate and put deletechars Delete some of the characters in. Notice if S for unicode String, then not supported  deletechars Parameter that can be used to translate a character to None The way to achieve the same function. It can also be used codecs Module to create more powerful translation table.  

String and a pair of encoding and decoding functions
S.encode([encoding,[errors]]) 
#  Among them encoding You can have multiple values, for example gb2312 gbk gb18030 bz2 zlib big5 bzse64 And so on. errors The default value is "strict" , which means UnicodeError . There are other possible values 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'  And all through codecs.register_error The registered value. This part is about codecs Module, not particularly understood  
S.decode([encoding,[errors]])

26. String test and judgment functions, which are not found in the string module, return bool values
S.startswith(prefix[,start[,end]]) 
# Whether or not to prefix At the beginning  
S.endswith(suffix[,start[,end]]) 
# In order to suffix At the end  
S.isalnum() 
# Whether it is all letters and Numbers and has at least one character  
S.isalpha() # Whether it is all letters and has at least one character  
S.isdigit() # Whether all Numbers and at least one character  
S.isspace() # Whether all white space characters and at least one character  
S.islower() #S Are all letters in lower case  
S.isupper() #S Is the letter in capital letters  
S.istitle() #S Is it capitalized 

27. String type conversion functions, which are only available in the string module
string.atoi(s[,base]) 
#base The default is 10 If for 0, then s Can is 012 or 0x23 This form of string, if yes 16 then s Can only be 0x23 or 0X12 This form of string  
string.atol(s[,base]) # into long 
string.atof(s[,base]) # into float

Again, string objects are immutable, meaning that after python creates a string, you cannot change a part of the character. Any of the above functions that change the string will return a new string, and the original string will not change. In fact, there is an alternative, you can use the function S=list(S) to change S into a list with a single character as a member, so you can use S[3]='a' to change the value, and then use S=" ".join(S) to restore the string

 


Related articles: