Python String functions

Source: Internet
Author: User

Generating string variables
str= ' python String function '

String length acquisition: Len (str)
Example: print '%s length=%d '% (Str,len (str))

Connection String
SSTR1 = ' strcat '
SSTR2 = ' Append '
SSTR1 + = SStr2
Print SSTR1

Copy string
#strcpy (SSTR1,SSTR2)
SSTR1 = ' strcpy '
SSTR2 = SStr1
SSTR1 = ' Strcpy2 '
Print SSTR2

Comparing strings
#strcmp (SSTR1,SSTR2)
SSTR1 = ' STRCHR '
SSTR2 = ' Strch '
Print CMP (SSTR1,SSTR2)

# Note that the output of the CMP function is the same as the strcmp of the C language. You can also use "aaa" = = "BBB" to compare strings.

Intercept string

Special Note: The subscript starts at 0; Str[0:3] does not contain a character with subscript 3.
str = ' 0123456789′
Print Str[0:3] #截取第一位到第三位的字符
Print str[:] #截取字符串的全部字符
Print Str[6:] #截取第七个字符到结尾
Print Str[:-3] #截取从头开始到倒数第三个字符之前
Print Str[2] #截取第三个字符
Print Str[-1] #截取倒数第一个字符
Print Str[::-1] #创造一个与原字符串顺序相反的字符串
Print Str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
Print str[-3:] #截取倒数第三位到结尾
Print str[:-5:-3] #逆序截取, what do you mean, you don't understand?

Search and Replace in string :
S.find (substr, [Start, [end]])    #返回S中出现substr的第一个字母的标号, Returns 1 if no substr is in S. The start and end functions are equivalent to searching in s[start:end] for
S.index (substr, [Start, [end]])    #与find (), except when there is no substr in S. Returns a run-time error
S.rfind (substr, [Start, [end]])    #返回S中最后出现的substr的第一个字母的标号, or 1 if there is no substr in S That is to say, the first occurrence of the substr from the right is the first letter of the
S.rindex (substr, [Start, [end]])
S.count (substr, [Start, [end]])      #计算substr在S中出现的次数
S.replace (Oldstr, Newstr, [Count])     #把S中的oldstr替换为newstr, Count is the number of replacements. This is a common form of substitution, and there are some functions to replace the special characters with
S.strip ([chars]) #把S中前后chars中有的字符全部去掉, which can be understood as replacing S chars with none
S.lstrip ([chars])
S.rstrip ([chars])
S.expandtabs ([tabsize])    #把S中的tab字符替换没空格, each tab is replaced by a tabsize space, and the default is 8


splitting and grouping of strings:
S.split ([Sep, [Maxsplit]]) #以sep为分隔符, divide s into a list. Maxsplit represents the number of splits. The default delimiter is a blank character
S.rsplit ([Sep, [Maxsplit]])
S.splitlines ([keepends]) #把S按照行分割符分为一个list, Keepends is a bool value that retains the row delimiter after each row is true.
S.join (seq) #把seq代表的序列-string sequence, connected by s
The mapping of the string, which contains two functions:
The String.maketrans (from, to) #返回一个256个字符组成的翻译表, where the characters from the from are converted to by one by one, so the from and to must be equal in length.
S.translate (Table[,deletechars]) # Use the above function for the post-natal translation table, translate s for translation, and delete the characters in the Deletechars. It is important to note that if S is a Unicode string, then the Deletechars parameter is not supported, and the same functionality can be achieved by translating a character to none. You can also use the functionality of the codecs module to create more powerful translation tables.

Character -Case transformations in strings:
S.lower () #小写
S.upper () #大写
S.swapcase () #大小写互换
S.capitalize () #首字母大写
String.capwords (S) #这是模块中的方法. It separates S with the split () function and then uses the
Capitalize () capitalize the initial letter and merge it with join ()
S.title () #只有首字母大写, the remainder is lowercase, this method is not in the module

String go to space and go to specify character
Go on both sides Space: Str.strip ()
Left space: Str.lstrip ()
Go right Space: Str.rstrip ()
Go to both sides of the string: Str.strip (' d '), corresponding to the Lstrip,rstrip
str= ' python String function '
print '%s strip=%s '% (Str,str.strip ())
str= ' python String function '
print '%s strip=%s '% (Str,str.strip (' d '))

Splits a string by a specified character array: Str.split (")


Stringencoding and decodingThe function:
S.encode ([encoding,[errors]]) # Where encoding can have a variety of 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 ', ' xmlcharrefre
S.encode ([encoding,[errors]]) # Where encoding can have a variety of values, such as gb2312 GBK gb18030 bz2 zlib Big5 bzse64, etc. are supported. The default value for errors is "strict", which means unicodeerror. Possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and all the values registered by Codecs.register_error. This section covers the codecs module, which is not a specific understanding
S.decode ([encoding,[errors]])
Test functions for strings, which are not in the string module and return bool values:
S.startwith (Prefix[,start[,end]) #是否以prefix开头
S.endwith (Suffix[,start[,end]) #以suffix结尾
S.isalnum () #是否全是字母和数字, and has at least one character
S.isalpha () #是否全是字母, and has at least one character
S.isdigit () #是否全是数字, and has at least one character
S.isspace () #是否全是空白字符, and has at least one character
S.islower () #S中的字母是否全是小写
S.isupper () #S中的字母是否便是大写
S.istitle () #S是否是首字母大写的

StringType ConversionsFunctions, these functions 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 it is 16 then s can only be 0x23 or 0x12 this form of string
String.atol (S[,base]) #转成long
String.atof (S[,base]) #转成float

The conversion of a Python string to a number into a string str ()
The string becomes a number string.atoi (S,[,base])//base is the binary cardinality
Floating-point conversion string.atof (s)


The alignment of the string at output :
S.ljust (Width,[fillchar]) #输出width个字符, s left-aligned, the insufficient portion is filled with Fillchar, the default is a space.
S.rjust (Width,[fillchar]) #右对齐
S.center (width, [Fillchar]) #中间对齐
S.zfill (width) #把S变成width长, and right-aligned, less part with 0 complement

Single quotation marks in a string, double quotation marks are escaped with \.

How to convert a string into a number?
int (' 1234 ')

In the string module there are
Import string
>>> a= "12345"
>>> Import String
>>> String.atoi (a)
12345
>>> b= "123.678"
>>> String.atof (b)
123.678

Convert to Long, with String.atol ()

Python String functions

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.