Introduction to several methods of manipulating strings in Python _python

Source: Internet
Author: User
Tags lowercase in python
  #! -*-coding:utf-8-*- 
  Import string 
  s = ' yes! This is a string ' 
  print ' original string: ' + s 
  print ' lowercase: ' + s.lower () 
  print ' uppercase: ' + s.upper () 
  print ' Case conversion: ' + S.swa Pcase () 
  print ' first letter: ' + s.capitalize () 
  print ' The first letter of each word: ' + s.title () 
   
  #各种对齐函数 
  print ' left-aligned: ' + s.ljust ( 40, '. ') #输出width个字符, S is left-aligned, and the insufficient portion is populated with char (a single character variable), and the default is a space. 
  print ' right-aligned: ' + s.rjust ('? ') 
  print ' middle alignment: ' + s.center ('! ') 
   
  #查找字符函数 
  print ' string and int-type variables do not wrap output method: ', 
  print s.find (' is ') #返回S中出现substr的第一个字母的标号, if substr is not in S, returns-1. The start and end functions are equivalent to S[start:end] 
  print s.count (' t ', 1,17) #计算substr在S中出现的次数 
  print S.expandtabs (8) # Replace the tab character in S with no space, each tab is replaced with tabsize space, default is 8 
  print s.join (' 01234 ') #把seq代表的序列--string sequence, with S to connect, run see effect 
   
  # String type conversion function 
  print string.atoi (' 8 ") 
   
  #另外, a continuous output of tips 
  print ' =? ' * 10 


Other actions of string and description (reference):

There are a variety of string manipulation functions in Python. In history, string classes have undergone a cycle of history in Python. At the very beginning, Python had a dedicated string module, the method to use string to import first, but later, as a result of the numerous Python user suggestions, starting from python2.0, the string method was replaced with S.method () As long as S is a string object that can be used without import. At the same time, in order to remain backward-compatible, the python still retains a string module, which is defined in the same way as S.method (), which eventually points to a function called with S.method (). Note that S.method () can invoke more methods than in string module, such as IsDigit (), Istitle (), and so on, only in S.method () mode.
For a String object, the first thought of the operation may be to calculate how many characters it has composed, it is easy to think of using S.len (), but this is wrong, it should be Len (S). Because Len () is a built-in function, included in the __builtin__ module. Python does not include Len () in the string type, which at first glance seems a little incomprehensible, in fact everything has its logical logic inside. Len () can not only compute the number of characters in a string, you can also calculate the number of members in the list, the number of members of the tuple, and so on, so it is not appropriate to count Len () in string, so one can use Len () as a common function, with overloads to implement different types of operations, Also, you can include a Len () function in each type that has the Len () operation. Python chooses the first solution. Similarly, there is the STR (ARG) function, which shows Arg as a string type.

Character-case transformation in a string:

S.lower () #小写
S.upper () #大写
S.swapcase () #大小写互换
S.capitalize () #首字母大写
String.capwords (S)
#这是模块中的方法. It separates S with the split () function, and then uses capitalize () to capitalize the first letter, then merge it with join ().
S.title () #只有首字母大写, the rest is lowercase, the module does not have this method


The alignment of the string at the time of output:

S.ljust (Width,[fillchar])
#输出width个字符, S left alignment, less than the Fillchar fill, the default is a space.
S.rjust (Width,[fillchar]) #右对齐
S.center (width, [Fillchar]) #中间对齐
S.zfill (width) #把S变成width长, and in the right alignment, insufficient parts with 0 complement

Search and Replace in strings:

S.find (substr, [Start, [end]]) 
#返回S中出现substr的第一个字母的标号, if there is no substr in S, return-1. The start and end functions are equivalent to searching for 
S.index (substr, [Start, [end]]) 
#与find () in S[start:end], except that when there is no substr in S, a run-time error is returned 
S.rfind (substr, [Start, [end]]) 
#返回S中最后出现的substr的第一个字母的标号, if there is no substr in S, return-1, That is to say, the first letter of the substr that appears from the right is 
s.rindex (substr, [Start, [end]]) 
s.count (substr, [Start, [end]]) Calculates the number of times substr appears in S 
s.replace (Oldstr, Newstr, [Count]) 
#把S中的oldstar替换为newstr, and Count is the number of substitutions. This is the general form of substitution, and some functions perform special character substitution 
S.strip ([chars]) 
#把S中前后chars中有的字符全部去掉, which can be understood to replace the chars with the None 
S.lstrip ( [chars]) 
S.rstrip ([chars]) 
s.expandtabs ([tabsize]) 
#把S中的tab字符替换成空格, each tab is replaced with a tabsize space and the default is 8 

String segmentation and Composition:

S.split ([Sep, [Maxsplit]]) 
#以sep为分隔符, dividing s into a list. Maxsplit represents the number of splits. The default delimiter is whitespace character 
s.rsplit ([Sep, [Maxsplit]]) 
s.splitlines ([keepends]) 
#把S按照行分割符分为一个list, Keepends is a bool value , the row delimiter is preserved if each row is true. 
s.join (seq) #把seq代表的序列--sequence of strings, connected with S 

The mapping of the string, which contains two functions:

The String.maketrans (from, to) 
#返回一个256个字符组成的翻译表, where the characters in the from are converted into to by one by one, so that from and to must be equal. 
s.translate (Table[,deletechars]) 
# Use the above function to translate the form, translate the S, and delete the characters from the Deletechars. Note that if S is a Unicode string, the Deletechars argument is not supported, and you can implement the same functionality in a way that translates a character to none. You can also use the features of the codecs module to create more powerful translation tables. 
The string also has a pair of coded and decoded functions: 

S.encode ([encoding,[errors]]) 
# where encoding can have multiple values, such as gb2312 GBK gb18030 bz2 zlib BIG5, etc. are supported. Errors The default value is "strict", meaning unicodeerror. Possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and all the values registered through Codecs.register_error. This section covers the codecs module, not the special understanding 

S.decode ([encoding,[errors]) 

The test function for the string, which is not in the string module, which returns a bool value:

S.startwith (Prefix[,start[,end]]) 
#是否以prefix开头 
s.endwith (Suffix[,start[,end])) 
#以suffix结尾 
S.isalnum () 
#是否全是字母和数字, and at least one character 
S.isalpha () #是否全是字母, and at least one character 
s.isdigit () #是否全是数字, and at least one character 
S.isspace () #是否全是空白字符, with at least one character 
s.islower () #S中的字母是否全是小写 
s.isupper () #S中的字母是否便是大写 
s.istitle () # S is the first letter of capital 

string-type conversion functions, which are only available in the string module:

String.atoi (S[,base]) 
#base默认为10, if 0, then s can be 012 or 0x23 This form of string, if 16 then s can only be 0x23 or 0x12 this form of string 
String.atol (S[,base]) #转成long 
string.atof (s[,base]) #转成float 

Again, the string object is immutable, meaning you can't change a part of the character after Python creates a string. Any of the above functions will return a new string after the string has been changed, and the source string has not changed. In fact, this is also a workaround, you can use the S=list (s) function to change S to a single character as a member of the list, so you can use the s[3]= ' a ' method of changing the value, and then use s= "". Join (s) revert to a string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.