Home > Article > Backend Development > Detailed explanation of Character string in Python with examples
The following editor will bring you an article on Character string in python (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look
1. Python string
String is the most commonly used data type in Python. We can use quotation marks (' or ") to create strings. l
Python does not support single character types, and single characters are also used as a string in Python.
>>> var1 = 'hello python' #定义字符串 >>> print(var1[0]) #切片截取,从0开始,不包括截取尾数 h >>> print(var1[0:5]) hello >>> print(var1[-6:]) python >>> var2 = var1[0:6]+'world' #截取字符并拼接赋值给新变量 >>> print(var2) hello world
2. Python escape character
\ : At the end of the line, it is the line continuation character
\\ : Backslash escape, output '\'
\' :Single quote escape
\":Double quote escape
\b :Backspace
\n :Line feed
\v :Vertical tab character
\t :Horizontal tab character
\r :Carriage return
\f :Page change
3. python string operators
(+) splicing, (*) repetition, ( []) index, ([:]) slicing, (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' not in var1 #判断字符串是否不在变量中 True >>> print("he\tllo \n") he llo >>> print(r"he\tllo \n") #原始输出字符串,也就是原始输出转义字符 he\tllo \n
4. Formatted strings
Python supports the output of formatted strings. Although this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %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 codes |
%s | Format string |
%d | Format integer |
%u | Format unsigned integer |
%o | Format unsigned octal number |
%x | Format unsigned hexadecimal number |
%X | Format unsigned hexadecimal number System number (uppercase) |
%f | Format floating point numbers, you can specify the precision after the decimal point |
%e | Use scientific notation to format floating point numbers |
%E | The function is the same as %e, use scientific notation to format floating point numbers |
%g | Abbreviation of %f and %e |
%G | Abbreviation of %f and %E |
%p | Format the address of a variable as a hexadecimal number |
Format operator Auxiliary instructions:
* | Define width or decimal point precision |
- | Used for left alignment |
+ | Display plus sign (+) in front of positive numbers |
Display spaces before positive numbers |
|
#Display zero ('0') before octal numbers, and before hexadecimal numbers Display '0x' or '0X' (depending on whether 'x' or 'X' is used) | |
0 | The displayed number is filled with '0' in front and Instead of the default space |
% | '%%' outputs a single '%' |
(var) | Map variable (dictionary parameter) |
m.n. | m is the minimum total width of the display, 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和%E的简写 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位 str: 888.089Since python2.6, the format string function str.format():usage has been added : It uses {} and : to replace % Positional parameters are not subject to order constraints, and can be {} empty, as long as there is a corresponding parameter value in the format. If the parameter value is not enough, an error will be reported. The parameter index starts from 0, and the incoming positional parameter list can be *list
In [27]: '{}+{}={}'.format(1,2,3) #格式化按顺序应用参数值 Out[27]: '1+2=3' In [28]: '{2}-{1}={0}'.format(1,2,3) #指定顺序应用参数值 Out[28]: '3-2=1' In [29]: '{0}+{0}={1}'.format(2,3) #指定参数可以重复使用 Out[29]: '2+2=3' In [30]: '{}+{}={}'.format(2,3) #如不指定顺序,format参数不够就会报错 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-30-29f40e412920> in <module>() ----> 1 '{}+{}={}'.format(2,3) IndexError: tuple index out of range In [31]: l1 = [2,4,8] In [32]: '{}*{}={}'.format(*l1) #使用列表引用参数值 Out[32]: '2*4=8' In [33]: dct = {'name':'python','age':20} #定义字典 In [35]: 'welcom to {name},age is {age}'.format(name='qi',age=28) #变量引用 Out[35]: 'welcom to qi,age is 28' In [36]: 'welcom to {name},age is {age}'.format(**dct) #使用**引用字典参数必须填写key值 Out[36]: 'welcom to python,age is 20' 填充与格式化: In [53]: "{0: >20}".format("string") #从0位开始已空格填充20宽度左对齐 Out[53]: ' string' In [54]: "{0:&>20}".format("string") Out[54]: '&&&&&&&&&&&&&&string' In [55]: "{0:#>20}".format("string") #使用#号会有个小bug ....: Out[55]: '##############string' In [60]: '{0:+<20}'.format("string") #向右对齐填充+ Out[60]: 'string++++++++++++++' In [61]: '{0:+^20}'.format("string") #剧中对齐填充+ Out[61]: '+++++++string+++++++' 精度与进制: >>> '{0:.3f}'.format(10/3) #小数位进度格式化 '3.333' >>> '{0:b}'.format(8) #格式化二进制 '1000' >>> '{0:o}'.format(9) #格式化八进制 '11' >>> '{0:x}'.format(26) #格式化十六进制 '1a' >>> '{0:,}'.format(123456789) #千分位格式化 '123,456,789' 使用索引: >>> l2 = ['AA',{'bb':'cc'},('d','e')] #列表索引引用 >>> 'outing:{0[0]}'.format(l2) 'outing:AA' >>> 'outing:{0[0]},{0[1]}'.format(l2) #将列表当成一个元素,在其中索引值 "outing:AA,{'bb': 'cc'}"
5. Python's string method
>>> s = 'i mi to' #将字符串的第一个字符改为大写 >>> s.capitalize() 'I mi to' >>> s = 'I MI TO' #将字符串所有字符改为小写 >>> s.casefold() 'i mi to' >>> s.center(15) #将字符串剧中,并用空格将字符串填充长度,如指定长度小于实际长度则没有效果 ' I MI TO ' >>> s = 'abcabcabcabc' #返回sub在字符串里出现的次数,start,end为可选参数,决定范围 >>> s.count('a',0,12) 4 >>> s.encode(encoding='utf-8',errors='strict') #以encoding指定的编码格式对字符串进行编码 b'abcabcabcabc' >>> s.endswith('abc',1,12) #检查字符串是否以sub结尾,是返回True,否返回False,start,end为可选参数,决定范围 True >>> s = 'a\tb\tc' >>> s.expandtabs(4) #把字符串的tab字符(\t)转化为空格,如不指定tabsize,默认为8个空格 'a b c' >>> s.find('b') #检测字符串是否在字符串中,如在则返回索引,否则返回-1,可指定起始值。 2 >>> s='hello python' >>> s.index('hello') # 类似find(),不同在于如果sub不在字符串中,返回异常 0 >>> s.isalnum() #有空格返回false False >>> s='hellopython' >>> s.isalnum() #如果字符串至少有一个字符,并且所有字符都是字母或数字则返回True,否则False True >>> s.isalpha() #如果字符串至少有一个字符,并且所有字符都是字母则返回True,否则False True >>> s = '123' >>> s.isdigit() #如果字符串只包含数字则返回True,否则返回False True >>> s = '123' >>> s.isdecimal() #如果字符串只包含十进制数字则返回True,否则返回False True >>> s= 'ox123' >>> s.isdecimal() False >>> s = '0.33' >>> s.isdecimal() False >>> s = 'abc' >>> s.islower() #如果字符中至少包含一个能区分大小写的字符,并且这些字符都是小写则返回True,否则返回Flase True >>> s = 'Abc' >>> s.islower() False >>> s = 'ABC' >>> s.isupper() #果字符中至少包含一个能区分大小写的字符,并且这些字符都是大写则返回True,否则返回Flase True >>> s = 'ABc' >>> s.isupper() False >>> >>> s = '123' >>> s.isnumeric() #如果字符串只包含数字字符,则返回True,否则返回False True >>> s = '123a' >>> s.isnumeric() False >>> 'def'.isidentifier() #判断字符串是否包含该语言的保留字 True >>> 'aaa'.isprintable() #判断是否可以打印 True >>> ''.isspace() False >>> ' '.isspace() #判断字符串中至少有一个字符且所有都是空格,否则返回false True >>> ' a'.isspace() False >>> 'Abc'.istitle() #判断是否是标题 格式,可以理解为首字母大写。 True >>> 'aBC'.istitle() False >>> s = '123' >>> '_'.join(s) #返回一个用指定字符串分隔的字,或者是将指定字符加入到另一个字符中。 '1_2_3' >>> s.join('abc') 'a123b123c' >>> s = 'ABC' >>> s.lower() #返回的是指定字符串的拷贝,并转化成小写 'abc' >>> s.ljust(10,'+') #可以指定宽度,以及填充字符串,返回的是按宽度,填充字符串格式化后的左对齐的字符串。 'ABC+++++++' >>> 'aaabccc'.partition('b') #在字符串中查找指定的字符,如找到则返回字符前部分,字符本身和后部分,如没找到则返回字符串和两个空字符串。 ('aaa', 'b', 'ccc') >>> 'aaabccc'.partition('e') ('aaabccc', '', '') >>> 'aaabccc'.rpartition('b') #与partition一样,但是是从右边开始 ('aaa', 'b', 'ccc') >>> 'aaabccc'.rpartition('c') ('aaabcc', 'c', '') >>> 'aaaaabbcc'.replace('a','A') #用指定字符串替换指定字符串,如果不指定替换次数,则替换所有 'AAAAAbbcc' >>> 'aaaaabbcc'.replace('a','A',2) 'AAaaabbcc' >>> 'aabbcc'.rfind('a') #返回指定子串的最高索引,如果没找到则返回-1,可以指定要开始替换的起始,结束位置。 1 >>> 'aabbcc'.rfind('e') -1 >>> 'aabbcc'.rindex('a') #与上面的rfind一样,只是如果没找到不是返回-1,而是触发错误 1 >>> 'aabbcc'.rindex('e') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> 'aa'.rjust(10,'+') #与ljust()相对应,右对齐 '++++++++aa' >>> 'aa'.ljust(10,'+') 'aa++++++++' >>> 'aabccbddbee'.split('b') ##按指定字符串对目标字符串进行切割,可以指定切割次数 ['aa', 'cc', 'dd', 'ee'] >>> 'aabccbddbee'.split('b',2) ['aa', 'cc', 'ddbee'] >>> 'aabccbddbee'.rsplit('b',2) #与split作用相同,但是从右侧开始 ['aabcc', 'dd', 'ee'] >>> ' aabb '.strip() #移除字符串两侧的指定字符串,默认移除空格,需要注意的是可以指定多个字符 'aabb' >>> ' aabb'.strip('b') ' aa' >>> ' aabb'.strip('ab') ' ' >>> 'beaacebb'.rstrip('eb') #与strip一样,从右侧删除指定字符,可以为多个 'beaac' >>> 'aa\nbb\ncc\ndd'.splitlines() #按换行符切割显示,如没指定keepends=True则将换行符移除。 ['aa', 'bb', 'cc', 'dd'] >>> 'aa\nbb\ncc\ndd'.splitlines(keepends=True) ['aa\n', 'bb\n', 'cc\n', 'dd'] >>> 'aabbc'.startswith('a') #判断字符串是否以某个字符开头,可以是多字符 True >>> 'aabbc'.startswith('b') False >>> 'aabbc'.startswith('aab') True >>> 'aaBBcc'.swapcase() #转换大小写 'AAbbCC' >>> 'wend is ok'.title() #标题格式,首字母大写,其它字符小写 'Wend Is Ok' >>> 'wend is ok'.upper() #将字符全部转换成大写 'WEND IS OK' >>> 'wend is ok'.zfill(20) #这里的z指zero,用0将字符填充到指定长度 '0000000000wend is ok'
The above is the detailed content of Detailed explanation of Character string in Python with examples. For more information, please follow other related articles on the PHP Chinese website!