An introduction to several methods of manipulating strings in Python

  • 2020-05-07 19:59:29
  • OfStack


  #! -*- coding:utf-8 -*- 
  import string 
  s = 'Yes! This is a string' 
  print ' Original string: ' + s 
  print ' Lower case: ' + s.lower() 
  print ' Capital: ' + s.upper() 
  print ' Case conversion: ' + s.swapcase() 
  print ' Capital letters: ' + s.capitalize() 
  print ' Capitalize the first letter of each word :' + s.title() 
   
  # Various alignment functions  
  print ' Left: ' + s.ljust(40,'.')# The output width A character, S Left - aligned, use less char( Single character variable ) Fill, default is space.  
  print ' Right alignment: ' + s.rjust(30,'?') 
  print ' Middle alignment: ' + s.center(28,'!') 
   
  # Find character function  
  print 'string and int Type variable output method without newline: ', 
  print s.find('is')# return S Appear in the substr The first 1 if S There is no substr It returns -1 . start and end The action is the same as in S[start:end] 
  print s.count('t',1,17) # To calculate substr in S Is the number of times  
  print s.expandtabs(8)# the S In the tab Character substitution no Spaces, each tab Replace with tabsize Space, by default 8 a  
  print s.join('01234') # the seq Represents a sequence -- a sequence of strings S connect , Operation effect  
   
  # String type conversion function  
  print string.atoi('10',8) 
   
  # In addition, 1 Three tips for continuous output  
  print '=?' * 10 


Other string operations and instructions (for reference) :

There are various string operation functions in python. Historically, the string class has undergone a history of reincarnation in python. At the very beginning, python had a dedicated string module, and import was the first method to use string. However, due to the recommendation of many python users, string method was called as S.method (), as long as S was a string object, instead of import. At the same time, in order to maintain backward compatibility, there is still one string module in python, where the methods defined are the same as S.method (), all of which end up pointing to the function called with S.method (). Note that S.method () can call more methods than string's module, such as isdigit(), istitle(), etc., which can only be called as S.method ().
The first thing that comes to mind for a string object might be to calculate how many characters it has. It's easy to think of S.len (), but that's wrong. len(S). This is because len() is a built-in function, which is included with the s 43en__ module. python does not include len() in the string type, which at first glance seems a little incomprehensible, but there is a logical reason for the 1 slice. len () can not only calculate the number of characters in a string, you can also calculate list membership, tuple membership and so on, so attach len () in string is inappropriate, so one can be the len () as a generic function, overloading is used to implement the different types of operations, and can in each len () type of operation, always include a len () function. python chose the first solution. Similarly, the str(arg) function represents arg in terms of string type.

Character case conversion in the string:

# lowercase S. lower ()
S. upper () # capitals
S.swapcase() # case - swap
S.capitalize() # begins with a capital letter
String.capwords(S)
This is the method in the module. It separates S with the split() function, then capitalizes the first letter with capitalize(), and finally merges join() into 1
S.title () # has only the first letter uppercase and the rest lowercase


String alignment on output:

S.ljust(width,[fillchar])
# output width characters, S left aligned, the insufficients are filled with fillchar, default is space.
S.rjust (width,[fillchar]) # right aligned
S.center(width, [fillchar]) # middle alignment
S.zfill(width) # changes S to width long and is aligned to the right

Search and replace in string:


S.find(substr, [start, [end]]) 
# return S Appear in the substr The first 1 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 Will return 1 Two runtime errors  
S.rfind(substr, [start, [end]]) 
# return S The last to appear in substr The first 1 if S There is no substr It returns -1 That is to say, from the right 1 Time in the 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 1 These functions perform the substitution of special characters  
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 Characters are replaced with Spaces, each tab Replace with tabsize Space, by default 8 a  

Segmentation and composition of strings:


S.split([sep, [maxsplit]]) 
# In order to sep For the separator, put S Divided into 1 a list . maxsplit Represents the number of partitions. The default separator is a blank character  
S.rsplit([sep, [maxsplit]]) 
S.splitlines([keepends]) 
# the S Divided by line separators 1 a list . keepends is 1 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  

mapping of the string, this 1 function contains two functions:


String.maketrans(from, to) 
# return 1 a 256 A translation table of characters, in which from The character in 11 I'm going to convert to 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.  
 There are strings 1 Functions for encoding and decoding:  

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 1 Part of it involves codecs Module, not particularly understood  

S.decode([encoding,[errors]]) 

Test functions for the string, which are not available in the string module, return the bool value:


S.startwith(prefix[,start[,end]]) 
# Whether or not to prefix At the beginning  
S.endwith(suffix[,start[,end]]) 
# In order to suffix At the end  
S.isalnum() 
# Is it all letters and Numbers, and at least there are 1 A character  
S.isalpha() # Whether it's all letters, and at least there are 1 A character  
S.isdigit() # Is it all Numbers and at least there are 1 A character  
S.isspace() # Are all white space characters and at least have them 1 A 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  

string type conversion functions, these functions only 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 

Once again, the string object is 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, the original string will not change. You can change S into a single-character list by using the function S=list(S). You can then change the value by using S[3]='a' and then using S=" ".join (S) to restore the string


Related articles: