Example of Python character string

Source: Internet
Author: User
Here is a small series for everyone to bring a Python character string (example). Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

1. Python string

The string is the most commonly used data type in Python. We can use quotation marks (' or ') to create a string, L

Python does not support single character types, and one character is also used as a string in Python.


>>> var1 = ' Hello python ' #定义字符串 >>> print (var1[0]) #切片截取, starting from 0, excluding truncated mantissa h>>> print (Var1[0:5]) hello>>> print (var1[-6:]) python>>> var2 = var1[0:6]+ ' world ' #截取字符并拼接赋值给新变量 >>> print (VAR2) Hello World

2. Python escape character

\: line-continuation character at end of row

\ \: Anti-slash escape, output ' \ '

\ ': Single quote escaping

\ ": Double quote Escape

\b: Backspace (BACKSPACE)

\ n: Line break

\v: Portrait tab

\ t: Horizontal tab

\ r: Enter

\f: Page Change

3. Python string operator

(+) splicing, (*) repetition, ([]) index, ([:]) slice, (in) member judgment, (not in) non-member judgment, (R/R) element output string


>>> var1 = ' Hello ' >>> var2 = ' python ' >>> print (var1+var2) #拼接字符串hellopython >>> Print (var1*3) #重复输出字符串hellohellohello >>> print (var1[0]) #索引字符串h >>> print (var1[3:]) #索引切片lo >  >> ' e ' in var1 #判断字符串是否在变量中True >>> ' P ' var1 #判断字符串是否不在变量中True >>> print ("He\tllo \ n") he Llo >>> print (r "He\tllo \ n") #原始输出字符串, which is the original output escape character He\tllo \ n

4. Formatting strings

Python supports the output of formatted strings. Although this may use a very complex expression, the most basic usage is to insert a value into a string that has the string format of%s.

In Python, string formatting uses the same syntax as the sprintf function in C.

Python string formatting symbols:

%c Formatting characters and their ASCII code
%s formatting strings
%d formatting integers
%u Formatting an unsigned integer
%o Formatting an unsigned octal number
%x formatting unsigned hexadecimal numbers
%x Format unsigned hexadecimal number (uppercase)
%f Format floating-point numbers to specify the precision after a decimal point
%e Format floating-point numbers with scientific notation
%E function with%e, format floating-point numbers with scientific notation
%g Shorthand for%f and%e
%G Shorthand for%f and%E
%p Format the address of a variable with hexadecimal number

Formatting operator Auxiliary directives:

* Define width or decimal precision
- Used for left justification
+ Show plus sign (+) in front of positive number
<sp> Show spaces in front of positive numbers
# Displays 0 (' 0 ') before the octal number, preceded by ' 0x ' or ' 0X ' in hexadecimal (depending on ' x ' or ' x ')
0 The displayed number is preceded by ' 0 ' instead of the default space
% ' percent ' output a single '% '
(VAR) mapping variables (dictionary parameters)
M.N. M is the minimum total width displayed, and n is the number of digits after the decimal point (if available)


>>> print ("ascii:%c"% ' s ') #格式化输出字符ascii:s>>> print ("ascii:%c"% ' 1 ') #格式化输出数字ascii:1>>> Print ("str:%s"% ' character string ') #格式化字符串str: Character string>>> print ("str:%d"%888) #格式化整数str:888> >> print ("str:%f"%888) #格式浮点数str:888.000000>>> print ("str:%e"%888) #格式化科学计数浮点数str:8.880000e+02> >> print ("str:%e"%888) #同上str:8.880000e+02>>> print ("str:%g"%888) #%f and%E abbreviated str:888>>> print ("str:%20f"%888.089) #定义20宽度输出str:888.089000>>> print ("str:%-20f"%888.089) #用左对齐str: 888.089000 >> > Print ("str:%+20f"%888.089) #在正数前显示加号str: +888.089000>>> print ("str:%+-20f"%888.089) #左对齐显示加号str: + 888.089000 >>> Print ("str:%020f"%888.089) #以0填充默认的空格str:0000000000888.089000>>> print ("str:%%% 20f "%888.089) #在数字前输入% str:% 888.089000>>> print (" str:%%%-20f "%888.089) #左对齐输出% str:%888.089000 >> > Print ("str:%20.3f"%888.089) #显示最小总宽度20, 3 digits after the decimal point str:888.089

Starting from python2.6, add the formatted string function Str.format ():

To use: It replaces% with {} and:

Positional parameters are not constrained by order, and can be {} null, as long as there is a corresponding parameter value in format, such as the parameter value is not enough error, parameter index from 0, passed in the location parameter list available * list


in [+]: ' {}+{}={} '. Format (No. 28): ' 1+2=3 ' in []: ' {2}-{1}={0} '. Format () ' 3-2=1 ' in []: ' {0}+{0}={1} '. Format (2,3) #指定参数可以重复使用Out [+]: ' 2+2=3 ' in []: ' {}+{}={} '. Format (2,3) #如不指定顺序, If the format parameter is insufficient, the error will be---------------------------------------------------------------------------Indexerror Traceback ( Most recent call last) <ipython-input-30-29f40e412920> in <module> ()----> 1 ' {}+{}={} '. Format (2,3) Indexerror:tuple index out of Rangein [+]: L1 = [2,4,8] in [+]: ' {}*{}={} '. Format (*L1) #使用列表引用参数值Out [+]: ' 2*4=8 ' in [33 ]: DCT = {' name ': ' Python ', ' age ': ' 35} #定义字典In [+]: ' welcom to {name},age are {age} '. Format (name= ' qi ', age=28) #变量引用Out []: ' Welcom to Qi,age is "in [+]: ' welcom to {name},age are {age} '. Format (**DCT) #使用 * * Reference dictionary parameter must be filled with key value out[36]: ' Welcom to Pytho N,age is 20 ' Fill and format: in [+]: ' {0: >20} '. Format ("string") #从0位开始已空格填充20宽度左对齐Out [+]: ' String ' in [si]: ' {0:&>20} ". Format (" string ") out[54]: ' &AMP;&AMP;&AMP;&AMP;&AMP;&AMP;&AMp;&&&&&&&string ' in []: ' {0:#>20} '. Format ("string") #使用 # number will have a small bug ....: out[55]: ' # # ########### #string ' in [+]: ' {0:+<20} '. Format ("string") #向右对齐填充 +out[60]: ' string++++++++++++++ ' in [61]: ' {0:+^20} '. Format ("string") #剧中对齐填充 +out[61]: ' +++++++string+++++++ ' precision with:>>> ' {0:.3f} '. Format (10/3) #小数位进度格式化 ' 3. 333 ' >>> ' {0:b} '. Format (8) #格式化二进制 ' + ' >>> ' {0:o} '. Format (9) #格式化八进制 ' one ' >>> ' {0:x} '. Format (+) #格式化十六进制 ' 1a ' >>> ' {0:,} '. Format (123456789) #千分位格式化 ' 123,456,789 ' using index:>>> l2 = [' AA ', {' BB ' : ' CC '}, (' d ', ' e ')] #列表索引引用 >>> ' outing:{0[0]} '. Format (L2) ' Outing:aa ' >>> ' outing:{0[0]},{0[1]} '. Format (L2) #将列表当成一个元素 in which the index value "outing:aa,{' BB ': ' CC '}"

5. Python string method


>>> s = ' i mi to ' #将字符串的第一个字符改为大写 >>> s.capitalize () ' I mi to ' >>> s = ' i mi to ' #将字符串所有字符改为小写 > >> s.casefold () ' I mi to ' >>> s.center (#将字符串剧中), with a space to fill the string with length, if the specified length is less than the actual length then no effect ' I mi to ' >>> s = ' Abcabcabcabc ' #返回sub在字符串里出现的次数, start,end for optional parameters, decision range >>> S.count (' A ', 0,12) 4>>> S.encode (encoding= ' Utf-8 ', errors= ' strict ') #以encoding指定的编码格式对字符串进行编码b ' abcabcabcabc ' >>> s.endswith (' abc ', 1,12) # Checks whether the string ends with a sub, returns True, no returns false,start,end as an optional parameter, determines the range true>>> s = ' A\TB\TC ' >>> s.expandtabs (4) # Converts the tab character of a string (\ t) to a space, such as not specifying Tabsize, the default is 8 spaces ' a b C ' >>> s.find (' B ') #检测字符串是否在字符串中, if the index is returned, otherwise returns-1, you can specify the starting value. 2>>> s= ' Hello python ' >>> s.index (' Hello ') # similar to find (), except that if the sub is not in the string, return exception 0 >>> s.isalnum () #有空格返回falseFalse >>> s= ' Hellopython ' >>> s.isalnum () #如果字符串至少有一个字符, and all characters are letters or numbers return true, otherwise falsetrue>>> S.isalpha () #如果字符串至少有一个字符, and all characters are alphabetic returns true, otherwise falsetrue>>> s = ' 123 ' &GT;>> s.isdigit () #如果字符串只包含数字则返回True, otherwise return falsetrue>>> s = ' 123 ' >>> s.isdecimal () # Returns True if the string contains only decimal digits, otherwise returns falsetrue>>> s= ' ox123 ' >>> s.isdecimal () false>>> s = ' 0.33 ' > >> S.isdecimal () false>>> s = ' abc ' >>> S.islower () #如果字符中至少包含一个能区分大小写的字符, and these characters are lowercase to return true, Otherwise return flasetrue>>> s = ' abc ' >>> S.islower () false>>> s = ' abc ' >>> S.isupper () # The fruit character contains at least one case-sensitive character, and the characters are uppercase to return true, otherwise return flasetrue>>> s = ' ABc ' >>> s.isupper () false>>> >>> s = ' 123 ' >>> s.isnumeric () #如果字符串只包含数字字符, returns true otherwise falsetrue>>> s = ' 123a ' >> > s.isnumeric () false>>> ' Def '. Isidentifier () #判断字符串是否包含该语言的保留字True >>> ' aaa '. isprintable () # Determine if you can print true>>> '. Isspace () false>>> ". Isspace () #判断字符串中至少有一个字符且所有都是空格, otherwise return falsetrue>> > ' a '. isspace () false>>> ' ABC '. Istitle () #判断是否是标题 format, which can be understood as the first letter capitalized. True>>> ' ABC '. IStitle () false>>> s = ' 123 ' >>> ' _ '. Join (s) #返回一个用指定字符串分隔的字, or add the specified character to another character. ' 1_2_3 ' >>> s.join (' abc ') ' a123b123c ' >>> s = ' abc ' >>> S.lower () #返回的是指定字符串的拷贝 and converted to lowercase ' abc ' >>> s.ljust (' + ') #可以指定宽度, as well as padding strings, returns a string that is left-aligned after the string is formatted by the width of the fill. ' abc+++++++ ' >>> ' AAABCCC '. partition (' B ') #在字符串中查找指定的字符, if found, returns the first part of the character, the character itself and the back part, and returns a string and two empty strings, if not found. (' AAA ', ' B ', ' CCC ') >>> ' AAABCCC '. partition (' E ') (' AAABCCC ', ' ', ') >>> ' AAABCCC '. Rpartition (' B ') # Same as partition, but starting from the right (' AAA ', ' B ', ' CCC ') >>> ' AAABCCC '. rpartition (' C ') (' aaabcc ', ' C ', ') >>> ' AAAAABBCC '. Replace (' A ', ' a ') #用指定字符串替换指定字符串, replace all ' aaaaabbcc ' >>> ' aaaaabbcc ' If you do not specify a replacement number. Replace (' A ', ' a ', 2) ' AAAAABBCC ' >>> ' aabbcc '. RFind (' a ') #返回指定子串的最高索引, if not found, returns-1, which specifies the starting and ending position to start the substitution. 1>>> ' AABBCC '. RFind (' e ') -1>>> ' aabbcc '. Rindex (' a ') #与上面的rfind一样, just if not found not return-1, but trigger error 1>> > ' AABBCC ' rindex (' e ') Traceback (most recent call last): File "<stdin>", LIne 1, in <module>valueerror:substring not found>>> ' AA '. Rjust (, ' + ') corresponds to #与ljust (), right-aligned ' ++++++++AA ' >>> ' AA '. Ljust (' + ') ' aa++++++++ ' >>> ' Aabccbddbee '. Split (' B ') # #按指定字符串对目标字符串进行切割, you can specify the number of cuts [' AA ' , ' CC ', ' dd ', ' ee ']>>> ' Aabccbddbee '. Split (' B ', 2) [' AA ', ' cc ', ' Ddbee ']>>> ' Aabccbddbee '. Rsplit (' B ', 2) #与split作用相同, but start from the right [' aabcc ', ' dd ', ' ee ']>>> ' aabb '. Strip () #移除字符串两侧的指定字符串, by default remove spaces, note that you can specify more than one character ' Aabb ' >>> ' Aabb ' strip (' B ') ' AA ' >>> ' Aabb '. Strip (' ab ') ' >>> ' Beaacebb '. Rstrip (' EB ') #与strip一样, Removes the specified character from the right, and can be used for multiple ' beaac ' >>> ' aa\nbb\ncc\ndd '. Splitlines () #按换行符切割显示 and remove newline characters if no keepends=true is specified. [' AA ', ' BB ', ' cc ', ' dd ']>>> ' aa\nbb\ncc\ndd '. Splitlines (keepends=true) [' aa\n ', ' bb\n ', ' cc\n ', ' DD ']>> > ' AABBC '. StartsWith (' a ') #判断字符串是否以某个字符开头, can be multi-character true>>> ' AABBC '. StartsWith (' B ') false>>> ' Aabbc '. StartsWith (' AaB ') true>>> ' aabbcc '. Swapcase () #转换大小写 ' aabbcc ' >>> ' Wend IS OK '. Title () #标题格式, first letter uppercase, other characters lowercase ' wend is ok ' >>> ' wend are OK '. Upper () #将字符全部转换成大写 ' wend is ok ' >>> ' wend ' Ok '. Zfill #这里的z指zero, fill the character with 0 to the specified length ' 0000000000wend is ok '

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.