首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基础知识(六)--字符串

Python基础知识(六)--字符串

作者头像
py3study
发布2020-01-08 23:08:58
5420
发布2020-01-08 23:08:58
举报
文章被收录于专栏:python3python3
#字符串  
 
#字符串是用固定的str数据类型表示的,用来存放Unicode字符序列  
#str数据类型可以用来创建一个字符串对象,参数为空时返回一个空字符串  
a = str()  
print(a)                        #  
a = str("abcdef")  
print(a)                        #abcdef  
#str()函数可以用来进行类型转换  
a = str(123)  
print(a)                        #123  
#字符串是使用引号创建的,可以使用双引号,也可以使用单引号,  
#字符串两端所用引号必须相同  
#还可以使用三引号包含的字符串,这是Python对两端都使用三个引号的字符串的叫法  
text = """A triple quoted string like this can include 'quotes' and  
"quotes" without formality. We can also escape newlines \  
so this particular string is actually only two lines long.""" 
#如果字符串中使用的引号与包含字符串所用引号不同时,  
#可以直接使用,如果相同时,需要进行转义  
a = "Single 'quotes' are fine; \"doubles\" must be escaped." 
b ='single \'quotes\' must be escaped; "doubles" are fine.' 
 
#在三引号内可以直接使用换行,通过\n可以在任何字符串中包含换行  
#Python字符串转义  
\newline            #忽略换行?  
\\                  #反斜杠  
\'                  #单引号  
\"                  #双引号  
\a                  #ASCII蜂鸣 (BEL)  
\b                  #ASCII退格(BS)  
\f                  #ASCII走纸(FF)  
\n                  #ASCII换行(LF)  
\n{name}            #给定名称的Unicode字符  
\ooo                #给定八进制的字符  
\r                  #ASCII回国符(CR)  
\t                  #ASCII制表符(TAB)  
\uhhhh              #给定16位十六进制的Unicode字符  
\Uhhhhhhhh          #给定32位十六进制的Unicode字符  
\v                  #ASCII垂直指标(VT)  
\xhh                #给定8位十六进制的Unicode字符 
#在使用正则表达式的时候,由于需要使用大量字面意义反斜杠,  
#由于每个反斜杠都需要进行转义处理,从而造成了不便:  
import re  
phone1 = re.compile("^((?:[(}\\d+[)])?\\s*\\d+(?:-\\d+)?)$")  
#解决的方法是使用原始字符串  
#这种引号或三引号包含的字符串的第一个引号由r引导  
phone2 = re.compile(r"((?:[(}\d+[)])?\s*\d+(?:-\d+)?)$")  
 
#如果有一个长字符串跨越了两行或更多行,但不使用三引号包含,有两种方法:  
t = "This is not the best way to join two long strings " + \  
    "together since it relies on ugly newline escaping" 
      
s = ("this is the nice way to join two long strings" 
     "together; it relies on string literal concatenation.")  
#第二种情况,用圆括号将其包含在一起,构成一个单独的表达式,  
#如果不使用圆括号就只会对第一个字符串赋值,  
#第二个字符串会引起IndentationError异常  
 
#.py文件默认使用UTF-8 Unicode编码,因此可以写入任何Unicode字符  
#(这点我就遇到过问题,出现SyntaxError: Non-UTF-8 code)难道是Eclipse搞的鬼?)  
#(改变文件编码可以解决这个问题)  
#(但IDLE支持倒是真的)  
euros = "€\N{euro sign}\u20AC\U000020AC" 
                          #Unicode字符非大小写敏感  
print(euros)              #€€€€  
#而且连标志符也可以  
姓名 = "张小三" 
print(姓名)               #张小三  
#也就是说支持中文变量名的,虽然这样用的人很少,但我倒是觉得以后可以这么试试了  
#如果想知道字符串中某个字符的Unicode字元,可以用内置的ord()函数  
print(ord(euros[0]))      #8364  
print(hex(ord(euros[0]))) #0x20ac  
#同样,也可以用表示有效字元的任意整数转换成Unicode字符  
#这需要使用内置chr()函数  
s = "anarchists are " + chr(8734) + chr(0x23B7)  
print(s)                        #anarchists are ∞⎷  
print(ascii(s))                 #'anarchists are \u221e\u23b7'  
#比较字符串  
#字符串支持的比较运算符包括:< <= == != > >=  
#对于使用Unicode的字符串,比较运算存在两个问题:  
#1.字符可以有三种不同的UTF-8编码字节的表示方式  
#  解决方法导入unicodedata模块  
#  以"NFKD"为第一个参数,调用unicodedata.normalize()  
#  该函数返回的UTF-8编码字节表示的字符串总是字节序列  
#2.有些字符的排序是特定于某种语言的,而有些字符并不具备有意义的排序位置  
 
 
#字符串分片与步距  
#序列中的单个数据或字符串中的单个字符可以用数据项存取操作符[]来提取  
#索引值从0开始,直到字符串长度-1  
#负索引值最后一个字符为-1,向前逐渐递减  
#存取超过索引范围的字符会产生IndexError  
#分片操作符的语法格式  
#seq[start:]                        #提取star开始到字符串结尾  
#seq[start:end]                     #提取start到end-1的字符串  
#seq[start:end:step]                #提取start到end-1的字符串,每次间隔step  
text = "abcdefghijklmnopqrstuvwxyz" 
print(text[0])                      #a  
print(text[0:])                     #abcdefghijklmnopqrstuvwxyz  
print(text[2:10])                   #cdefghij  
print(text[:20])                    #abcdefghijklmnopqrst  
print(text[::2])                    #acegikmoqsuwy  
print(text[10::2])                  #kmoqsuwy  
print(text[10:26:2])                #kmoqsuwy  
print(text[26::-1])                 #zyxwvutsrqponmlkjihgfedcba  
print(text[::-1])                   #zyxwvutsrqponmlkjihgfedcba  
 
#字符串操作符与方法  
#字符串是固定序列,所有用于固定序列的功能都可用于字符串  
#包括in进行成员关系测试,+=进行追加操作  * 进行复制  *= 进行增加的复制  
subtext = "def" 
print(subtext in text)              #True  
subtext += "ghi" 
print(subtext)                      #defghi  
subtext *= 3 
print(subtext)                      #defghidefghidefghi 
#字符串方法  
#--------------------------------------------------------------------  
s.capitalize()          #返回字符串s的副本,并将首字符大写  
text = "this is a test text" 
print(text.capitalize())            #This is a test text  
#--------------------------------------------------------------------  
s.center(width, char)   #返回一个长度为width的字符串  
                        #字符串s在返回字符串的中间位置  
                        #其余部份用char添充,char默认为空格  
s = "abd" 
print(s.center(20))                 #        abd           
print(s.center(20, "*"))            #********abd*********  
#--------------------------------------------------------------------  
s.count(t, start, end)  #返回在s字符串中,start:end分片中,  
                        #子串t出现的次数  
s = "abcdabcdabcd" 
s.count("bc")                       #3  
s.count("bcda")                     #2  
s.count("bcda", 1, 8)               #1  
#--------------------------------------------------------------------  
s.encode(encoding, err) #返回一个bytes对象用指定编码格式来表示该字符串  
                        #并根据可选的err处理错误  
s = "中国" 
print(s.encode(encoding='utf_8', errors='strict'))  
                                    #b'\xe4\xb8\xad\xe5\x9b\xbd'   
print(s.encode(encoding='GB2312', errors='strict'))  
                                    #b'\xd6\xd0\xb9\xfa'  
print(s.encode(errors='strict'))    #b'\xe4\xb8\xad\xe5\x9b\xbd'  
                                    #默认的encoding是'utf_8'  
#--------------------------------------------------------------------  
s.endswith(x, start, end)   #如果在s或s[start:end]分片中从字符串x或  
                            #元组x中的任意字符串结尾,则返回True,否则返回False  
s = "×××" 
x = "国" 
print(s.endswith(x))                #True  
print(s.endswith(x, 2, 5))          #False  
x = ('一', '国')  
print(s.endswith(x))                #True  
#--------------------------------------------------------------------  
s.expandtabs(size)      #返回s的一个副本,其中制表符用8(默认)或size个空格替换  
                        #这个替换不是直接在tab的位置上插入size个空格,而是与前文相关联计算空格数  
s = "abc\tdef\tghi" 
print(s.expandtabs(4))              #abc def ghi  
print(s.expandtabs(8))              #abc     def     ghi  
print(s.expandtabs())               #abc     def     ghi  
#--------------------------------------------------------------------  
s.find(t, start, end)   #返回t在s或s[start:end]之中的最左位置,如果没有找到返回-1  
                        #使用s.rfind()可以返回相应的最右位置  
s = "this is a test text" 
print(s.find('is'))                 #2  
print(s.rfind('is'))                #5  
#--------------------------------------------------------------------  
s.format(...)           #格式化字符串,这个在后面详细解释  
#--------------------------------------------------------------------  
s.index(t, start, end)  #返回t在s或s[start:end]之中的最左位置,如果没有找到返回ValueError  
                        #使用s.rindex()可以从最右边开始搜索  
                        #用法同s.find()                                
#--------------------------------------------------------------------  
s.isalnum()             #如果s非空,并且其中每个字符都是字母数字的就返回True  
s = "abd123" 
print(s.isalnum())                  #True  
s += "_" 
print(s.isalnum())                  #False  
#--------------------------------------------------------------------  
s.isalpha()             #如果s非空,并且其中每个字符都是字母的就返回True  
s = "abd" 
print(s.isalnum())                  #True  
s += "123" 
print(s.isalnum())                  #False  
#--------------------------------------------------------------------  
s.isdecimal()           #如果s非空,并且每个字符都是Unicode的基数为10的数字就返回True  
s = "1234" 
print(s.isdecimal())                #True  
s = "0x1304" 
print(s.isdecimal())                #False  
#--------------------------------------------------------------------  
s.isdigit()             #如果非空,并且每个字符都是ASCII数字,则返回True  
s = "1234" 
print(s.isdigit())                  #True  
s += "a" 
print(s.isdigit())                  #False  
#--------------------------------------------------------------------  
s.isidentifier()        #如果s非空,并且是一个有效的标识符,则返回True  
s = "abc" 
print(s.isidentifier())             #True  
s = "abc#%^#" 
print(s.isidentifier())             #False  
#--------------------------------------------------------------------  
s.islower()             #如果s有至少一个小写字符,并且所有小写字符都是小写就返回True  
s = "abc" 
print(s.islower())                  #True  
s = "Abc" 
print(s.islower())                  #False  
s = "123" 
print(s.islower())                  #False  
#--------------------------------------------------------------------  
s.isnumeric()           #同s.isdigit(),字符为Unicode字符  
#--------------------------------------------------------------------  
s.isprintable()         #如果s非空,并且每个字符都是可打印字符,  
                        #包括空格但不包括换行,则返回True  
s = "this is a text" 
print(s.isprintable())              #True  
s = "this is a text\n" 
print(s.isprintable())              #False  
#--------------------------------------------------------------------  
s.isspace()             #如果s非空,并且所有字符都是空白,则返回True  
s = "   " 
print(s.isspace())                  #True  
s = "  1 " 
print(s.isspace())                  #False  
#--------------------------------------------------------------------  
s.istitle()             #如果s是非空的且首字母大写的字符串就返回True  
s = "This is a test" 
print(s.istitle())                  #False  
s = "This Is A Test" 
print(s.istitle())                  #True  
#--------------------------------------------------------------------  
s.isupper()             #如果s有至少一个可大写字符且所有可大写字符均为大写则返回True  
                        #可参考s.islower()  
#--------------------------------------------------------------------  
s.join(seq)             #返回序列中所有项连接起来的结果,  
                        #并以s(可以为空)在每两项之间分隔  
s = "*" 
seqs = ("this", "is", "a", "test")  
print(s.join(seqs))                 #this*is*a*test  
print(" ".join(seqs))               #this is a test  
print("".join(seqs))                #thisisatest  
print(" ".join(["this", "is", "a", "test"]))  
                                    #this is a test  
#--------------------------------------------------------------------  
s.ljust(width, char)    #返回一个长度为width的字符串,并以char来添充s左侧  
                        #可参考s.center(),s.rjust()为右添充  
#--------------------------------------------------------------------  
s.lower()               #将s中的字符变为小写  
s = "ABC123" 
print(s.lower())                    #abc123  
#--------------------------------------------------------------------  
s.maketrans()           #与s.translate()对应,可以产生一个转换表  
a = "abcde" 
b = "Hello" 
x = a.maketrans(a, b)  
print(a.translate(x))               #Hello  
                        #貌似可以进行替换,或是小小的加密也不错  
#--------------------------------------------------------------------  
s.partition(t)          #返回三个字符串的无级,分别是:  
                        #s中在t子串之前的部分  
                        #t  
                        #s中在t子串之后的部分  
                        #如果t不在s中,则返回s与两个空字符串  
                        #使用s.lpartition(t)可以在s最右边分区  
s = "My country is China" 
t = "country" 
print(s.partition(t))               #('My ', 'country', ' is China')  
t = "ABCD" 
print(s.partition(t))               #('My country is China', '', '')  
t = "is" 
print(s.rpartition(t))              #('My country ', 'is', ' China')  
#--------------------------------------------------------------------  
s.replace(t, u, n)      #返回字符串s的一个副本,其中每个或n个t用u替换  
s = "this is a text" 
print(s.replace("is", "Is"))        #thIs Is a text  
print(s.replace("is", "Is", 1))     #thIs is a text  
#--------------------------------------------------------------------  
s.split(t, n)           #返回一个字符串列表,在t处最多分割n次  
                        #如果n没指定,就尽可能分割多次  
                        #如果t没指定,就以空白处分割  
                        #s.rsplit(t, n)是从右侧开始分割,只有指定n,  
                        #且n小于可分割的最大次数时才有效  
s = "this is a test text" 
print(s.split("s"))                 #['thi', ' i', ' a te', 't text']  
print(s.split('s', 2))              #['thi', ' i', ' a test text']  
print(s.rsplit('s', 2))             #['this i', ' a te', 't text']  
#--------------------------------------------------------------------  
s.splitlines(f)         #返回的行终结符处分割产生的行列表  
                        #并剥离行终结符(除非f为True)  
 
print(s.splitlines())               #['this', 'is', 'a', 'test', 'text']  
print(s.splitlines(True))           #['this\n', 'is\n', 'a\n', 'test\n', 'text']  
#--------------------------------------------------------------------  
s.startswith(x, start, end)  
                        #如果字符串s或s[start:end]是以字符串x,  
                        #或元组中任一项开始,则返回True,否则返回False  
                        #可参考s.endswith()  
#--------------------------------------------------------------------  
s.strip(chars)          #将字符串开始和结尾处的chars中的字符移除  
                        #chars默认为空格  
                        #s.lstrip(chars)为去除字符串开始处的chars  
                        #s.rstrip(chars)为去除字符串结尾处的chars  
print(" my name is Xiaoming. ".strip())  
                                    #my name is Xiaoming.   
print(" my name is Xiaoming. ".lstrip())  
                                    #my name is Xiaoming.  
print(" my name is Xiaoming. ".rstrip())  
                                    # my name is Xiaoming.  
#--------------------------------------------------------------------  
s.swepcase()            #将字符串中大写转换成小写,小写转换成大写  
s = "This Is A Test Text" 
print(s.swapcase())                 #tHIS iS a tEST tEXT  
#--------------------------------------------------------------------  
s.title()               #将每个单词的首字母转成大写,其它字母转成小写  
s ="tHIS iS a tEST tEXT" 
print(s.title())                    #This Is A Test Text  
#--------------------------------------------------------------------  
s.upper()               #将字符全部转换成大写,可参考s.lower()  
#--------------------------------------------------------------------  
s.zfill(width)          #返回s的副本,如果s长度小于width则在开始处添加0使之长度为width  
s = "test" 
print(s.zfill(15))                  #00000000000test  
#-------------------------------------------------------------------- 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档