Example explanation of Character string in python

黄舟
Release: 2017-09-25 11:25:12
Original
1387 people have browsed it

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
Copy after login

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
Copy after login

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:

%cFormatting characters and their ASCII codes
%sFormat string
%dFormat integer
%uFormat unsigned integer
%oFormat unsigned octal number
%xFormat unsigned hexadecimal number
%XFormat unsigned hexadecimal number System number (uppercase)
%fFormat floating point numbers, you can specify the precision after the decimal point
%eUse scientific notation to format floating point numbers
%EThe function is the same as %e, use scientific notation to format floating point numbers
%gAbbreviation of %f and %e
%GAbbreviation of %f and %E
%pFormat 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, before hexadecimal numbers Display '0x' or '0X' (depending on whether 'x' or 'X' is used)
0The 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.089
Copy after login

Since 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 &#39;{}+{}={}&#39;.format(2,3)
IndexError: tuple index out of range

In [31]: l1 = [2,4,8] 
In [32]: &#39;{}*{}={}&#39;.format(*l1) #使用列表引用参数值
Out[32]: &#39;2*4=8&#39;

In [33]: dct = {&#39;name&#39;:&#39;python&#39;,&#39;age&#39;:20} #定义字典
In [35]: &#39;welcom to {name},age is {age}&#39;.format(name=&#39;qi&#39;,age=28) #变量引用
Out[35]: &#39;welcom to qi,age is 28&#39;

In [36]: &#39;welcom to {name},age is {age}&#39;.format(**dct) #使用**引用字典参数必须填写key值
Out[36]: &#39;welcom to python,age is 20&#39;

填充与格式化:
In [53]: "{0: >20}".format("string") #从0位开始已空格填充20宽度左对齐
Out[53]: &#39;  string&#39;

In [54]: "{0:&>20}".format("string")
Out[54]: &#39;&&&&&&&&&&&&&&string&#39;

In [55]: "{0:#>20}".format("string") #使用#号会有个小bug
 ....: 
Out[55]: &#39;##############string&#39;

In [60]: &#39;{0:+<20}&#39;.format("string") #向右对齐填充+
Out[60]: &#39;string++++++++++++++&#39;

In [61]: &#39;{0:+^20}&#39;.format("string") #剧中对齐填充+
Out[61]: &#39;+++++++string+++++++&#39;

精度与进制:
>>> &#39;{0:.3f}&#39;.format(10/3) #小数位进度格式化
&#39;3.333&#39;
>>> &#39;{0:b}&#39;.format(8) #格式化二进制
&#39;1000&#39;
>>> &#39;{0:o}&#39;.format(9) #格式化八进制
&#39;11&#39;
>>> &#39;{0:x}&#39;.format(26) #格式化十六进制
&#39;1a&#39;
>>> &#39;{0:,}&#39;.format(123456789) #千分位格式化
&#39;123,456,789&#39;

使用索引:
>>> l2 = [&#39;AA&#39;,{&#39;bb&#39;:&#39;cc&#39;},(&#39;d&#39;,&#39;e&#39;)] #列表索引引用
>>> &#39;outing:{0[0]}&#39;.format(l2) 
&#39;outing:AA&#39;
>>> &#39;outing:{0[0]},{0[1]}&#39;.format(l2) #将列表当成一个元素,在其中索引值
"outing:AA,{&#39;bb&#39;: &#39;cc&#39;}"
Copy after login

5. Python's string method


>>> s = &#39;i mi to&#39; #将字符串的第一个字符改为大写
>>> s.capitalize()
&#39;I mi to&#39;

>>> s = &#39;I MI TO&#39; #将字符串所有字符改为小写
>>> s.casefold()
&#39;i mi to&#39;

>>> s.center(15) #将字符串剧中,并用空格将字符串填充长度,如指定长度小于实际长度则没有效果
&#39; I MI TO &#39;

>>> s = &#39;abcabcabcabc&#39; #返回sub在字符串里出现的次数,start,end为可选参数,决定范围
>>> s.count(&#39;a&#39;,0,12)
4
>>> s.encode(encoding=&#39;utf-8&#39;,errors=&#39;strict&#39;) #以encoding指定的编码格式对字符串进行编码
b&#39;abcabcabcabc&#39;
>>> s.endswith(&#39;abc&#39;,1,12) #检查字符串是否以sub结尾,是返回True,否返回False,start,end为可选参数,决定范围
True

>>> s = &#39;a\tb\tc&#39;
>>> s.expandtabs(4) #把字符串的tab字符(\t)转化为空格,如不指定tabsize,默认为8个空格
&#39;a b c&#39;

>>> s.find(&#39;b&#39;) #检测字符串是否在字符串中,如在则返回索引,否则返回-1,可指定起始值。
2

>>> s=&#39;hello python&#39;
>>> s.index(&#39;hello&#39;) # 类似find(),不同在于如果sub不在字符串中,返回异常
0 

>>> s.isalnum() #有空格返回false
False
>>> s=&#39;hellopython&#39;
>>> s.isalnum() #如果字符串至少有一个字符,并且所有字符都是字母或数字则返回True,否则False
True
>>> s.isalpha() #如果字符串至少有一个字符,并且所有字符都是字母则返回True,否则False
True

>>> s = &#39;123&#39;
>>> s.isdigit() #如果字符串只包含数字则返回True,否则返回False
True

>>> s = &#39;123&#39;
>>> s.isdecimal() #如果字符串只包含十进制数字则返回True,否则返回False
True
>>> s= &#39;ox123&#39;
>>> s.isdecimal()
False
>>> s = &#39;0.33&#39;
>>> s.isdecimal()
False

>>> s = &#39;abc&#39;
>>> s.islower() #如果字符中至少包含一个能区分大小写的字符,并且这些字符都是小写则返回True,否则返回Flase
True
>>> s = &#39;Abc&#39;
>>> s.islower()
False

>>> s = &#39;ABC&#39;
>>> s.isupper() #果字符中至少包含一个能区分大小写的字符,并且这些字符都是大写则返回True,否则返回Flase
True
>>> s = &#39;ABc&#39;
>>> s.isupper()
False
>>> 

>>> s = &#39;123&#39;
>>> s.isnumeric() #如果字符串只包含数字字符,则返回True,否则返回False
True
>>> s = &#39;123a&#39;
>>> s.isnumeric()
False

>>> &#39;def&#39;.isidentifier() #判断字符串是否包含该语言的保留字
True

>>> &#39;aaa&#39;.isprintable() #判断是否可以打印
True

>>> &#39;&#39;.isspace()
False
>>> &#39; &#39;.isspace() #判断字符串中至少有一个字符且所有都是空格,否则返回false
True
>>> &#39; a&#39;.isspace()
False

>>> &#39;Abc&#39;.istitle() #判断是否是标题 格式,可以理解为首字母大写。
True
>>> &#39;aBC&#39;.istitle()
False

>>> s = &#39;123&#39;
>>> &#39;_&#39;.join(s) #返回一个用指定字符串分隔的字,或者是将指定字符加入到另一个字符中。
&#39;1_2_3&#39;
>>> s.join(&#39;abc&#39;)
&#39;a123b123c&#39;

>>> s = &#39;ABC&#39;
>>> s.lower() #返回的是指定字符串的拷贝,并转化成小写
&#39;abc&#39;

>>> s.ljust(10,&#39;+&#39;) #可以指定宽度,以及填充字符串,返回的是按宽度,填充字符串格式化后的左对齐的字符串。
&#39;ABC+++++++&#39;

>>> &#39;aaabccc&#39;.partition(&#39;b&#39;) #在字符串中查找指定的字符,如找到则返回字符前部分,字符本身和后部分,如没找到则返回字符串和两个空字符串。
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.partition(&#39;e&#39;)
(&#39;aaabccc&#39;, &#39;&#39;, &#39;&#39;)

>>> &#39;aaabccc&#39;.rpartition(&#39;b&#39;) #与partition一样,但是是从右边开始
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.rpartition(&#39;c&#39;)
(&#39;aaabcc&#39;, &#39;c&#39;, &#39;&#39;)


>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;) #用指定字符串替换指定字符串,如果不指定替换次数,则替换所有
&#39;AAAAAbbcc&#39;
>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;,2)
&#39;AAaaabbcc&#39;

>>> &#39;aabbcc&#39;.rfind(&#39;a&#39;) #返回指定子串的最高索引,如果没找到则返回-1,可以指定要开始替换的起始,结束位置。
1
>>> &#39;aabbcc&#39;.rfind(&#39;e&#39;)
-1
>>> &#39;aabbcc&#39;.rindex(&#39;a&#39;) #与上面的rfind一样,只是如果没找到不是返回-1,而是触发错误
1
>>> &#39;aabbcc&#39;.rindex(&#39;e&#39;)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: substring not found

>>> &#39;aa&#39;.rjust(10,&#39;+&#39;) #与ljust()相对应,右对齐
&#39;++++++++aa&#39;
>>> &#39;aa&#39;.ljust(10,&#39;+&#39;)
&#39;aa++++++++&#39;

>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;) ##按指定字符串对目标字符串进行切割,可以指定切割次数
[&#39;aa&#39;, &#39;cc&#39;, &#39;dd&#39;, &#39;ee&#39;]
>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;,2)
[&#39;aa&#39;, &#39;cc&#39;, &#39;ddbee&#39;]

>>> &#39;aabccbddbee&#39;.rsplit(&#39;b&#39;,2) #与split作用相同,但是从右侧开始
[&#39;aabcc&#39;, &#39;dd&#39;, &#39;ee&#39;]

>>> &#39; aabb &#39;.strip() #移除字符串两侧的指定字符串,默认移除空格,需要注意的是可以指定多个字符
&#39;aabb&#39;
>>> &#39; aabb&#39;.strip(&#39;b&#39;)
&#39; aa&#39;
>>> &#39; aabb&#39;.strip(&#39;ab&#39;)
&#39; &#39;
>>> &#39;beaacebb&#39;.rstrip(&#39;eb&#39;) #与strip一样,从右侧删除指定字符,可以为多个
&#39;beaac&#39;

>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines() #按换行符切割显示,如没指定keepends=True则将换行符移除。
[&#39;aa&#39;, &#39;bb&#39;, &#39;cc&#39;, &#39;dd&#39;]
>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines(keepends=True)
[&#39;aa\n&#39;, &#39;bb\n&#39;, &#39;cc\n&#39;, &#39;dd&#39;]

>>> &#39;aabbc&#39;.startswith(&#39;a&#39;) #判断字符串是否以某个字符开头,可以是多字符
True
>>> &#39;aabbc&#39;.startswith(&#39;b&#39;)
False
>>> &#39;aabbc&#39;.startswith(&#39;aab&#39;)
True

>>> &#39;aaBBcc&#39;.swapcase() #转换大小写
&#39;AAbbCC&#39;

>>> &#39;wend is ok&#39;.title() #标题格式,首字母大写,其它字符小写
&#39;Wend Is Ok&#39;

>>> &#39;wend is ok&#39;.upper() #将字符全部转换成大写
&#39;WEND IS OK&#39;

>>> &#39;wend is ok&#39;.zfill(20) #这里的z指zero,用0将字符填充到指定长度
&#39;0000000000wend is ok&#39;
Copy after login

The above is the detailed content of Example explanation of Character string in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template