当前位置: 首页 > 后端技术 > Python

(Python基础教程七)Python字符串操作

时间:2023-03-26 12:17:39 Python

Python基础教程在SublimeEditor中配置Python环境给Python代码添加注释使用Python数据类型Python关键字Python字符串操作Python列表操作Python中的元组操作Pythonmax()和min()–查找列表或数组中的最大值和最小值Python查找最大的N(topN)或最小的N项Python读写CSV文件Python使用httplib2–HTTPGET和POST示例Python将元组拆箱为变量或parameterPythonunboxingatuple–toomanyvaluestounpackPythonmultidict示例–将单个键映射到字典中的多个值PythonOrderedDict–有序字典Python字典交集–比较两个字典Python优先级队列示例Python中的字符串文字是:表示用单引号或双引号括起来的Unicode字符的字节数组无限长度的字符串文字str='helloworld'str="helloworld"a使用三个单引号或三个双引号创建多行字符串。多行字符串字面量str='''Sayhellotopythonprogramming'''str="""Sayhellotopythonprogramming"""Python没有字符数据类型,单个字符是长度为1的字符串。2.子串或切片By使用切片语法,我们可以获得一系列字符。索引从零开始。str[m:n]返回从位置2(含)到5(不含)的字符串。substringfromindex2to5str='helloworld'print(str[2:5])#llo负切片将从末尾返回子串。substringfromindex-5to-2str='helloworld'print(str[-5:-2])#worstr[-m:-n]返回从位置-5(不包括)到-2(包括)的字符串。3.字符串作为数组在python中,字符串被表示为数组。方括号可用于访问字符串的元素。字符在第n个位置str='helloworld'print(str[0])#hprint(str[1])#eprint(str[2])#lprint(str[20])#IndexError:stringindexout范围4。Stringlengthlen()函数返回字符串的长度:stringlengthstr='helloworld'print(len(str))#115.字符串格式化要在python中格式化s字符串,请在字符串中要求的{}位置使用占位符.将参数传递给format()函数以使用该值格式化字符串。我们可以在占位符中传递参数位置(从零开始)。stringformat()age=36name='Lokesh'txt="Mynameis{}andmyageis{}"print(txt.format(name,age))#MynameisLokeshandmyageis36txt="My年龄是{1},名字是{0}"print(txt.format(name,age))#我的年龄是36岁,名字是Lokesh6。字符串方法6.1。capitalize()它返回一个字符串,其中给定字符串的第一个字符被转换为大写。当第一个字符不是字母时,它返回相同的字符串。stringcapitalize()name='lokeshgupta'print(name.capitalize())#Lokeshguptatxt='38yrsoldlokeshgupta'print(txt.capitalize())#38yrsoldlokeshgupta6.2.casefold()它返回一个字符串,其中所有字符都是给定字符串的小写字母。Stringcasefold()txt='MyNameisLokeshGupta'print(txt.casefold())#mynameislokeshgupta6.3.center()使用指定字符(默认为空格)作为填充字符,使字符串对齐到中心。在给定的示例中,输出总共需要20个字符,其中包含“helloworld”。Stringcentertxt="helloworld"x=txt.center(20)print(x)#'helloworld'6.4.count()返回指定值在字符串中出现的次数。它有两种形式:count(value)-在字符串中搜索的值。count(value,start,end)-要在字符串中搜索的值,搜索从开始位置开始到结束位置。Stringcount()txt="helloworld"print(txt.count("o"))#2print(txt.count("o",4,7))#16.5。encode()它使用指定的编码对字符串进行编码。如果未指定编码,将使用UTF-8。stringencode()txt="Mynameis?mber"x=txt.encode()print(x)#b'Mynameis\xc3\xa5mber'6.6.endswith()True如果字符串以指定值结尾,则返回,否则返回False。stringendswith()txt="helloworld"print(txt.endswith("world"))#Trueprint(txt.endswith("planet"))#False6.7.expandtabs()它将制表符大小设置为指定的空格数。Stringexpandtabs()txt="hello\tworld"print(txt.expandtabs(2))#'helloworld'print(txt.expandtabs(4))#'helloworld'print(txt.expandtabs(16))#'你好世界'6.8。find()它找到指定值的第一次出现。如果字符串中不存在指定值,则返回-1。find()与index()方法相同,唯一的区别是index()如果找不到值会抛出异常。Stringfind()txt="MynameisLokeshGupta"x=txt.find("e")print(x)#66.9.format()它格式化指定的字符串并将占位符放在字符串中插值参数值。stringformat()age=36name='Lokesh'txt="Mynameis{}andmyageis{}"print(txt.format(name,age))#我的名字是Lokesh,年龄是366.10。format_map()用于返回字典键的值以格式化具有命名占位符的字符串。Stringformat_map()params={'name':'LokeshGupta','age':'38'}txt="我的名字是{name},年龄是{age}"x=txt.format_map(params)print(x)#我叫LokeshGupta,年龄386.11。index()查找给定字符串中指定值的第一次出现。如果找不到正在搜索的值,则会抛出异常。Stringindex()txt="MynameisLokeshGupta"x=txt.index("e")print(x)#6x=txt.index("z")#ValueError:substringnotfound6.12.isalnum()它检查字母数字字符串。如果所有字符都是字母数字,即字母(a-zA-Z)和数字,则为真,它将返回(0-9)。Stringisalnum()print("LokeshGupta".isalnum())#Trueprint("LokeshGupta".isalnum())#False-包含space6.13。isalpha()True如果所有字符都是字母则返回它,即字母(a-zA-Z)。Stringisalpha()print("LokeshGupta".isalpha())#Trueprint("LokeshGupta".isalpha())#False-包含spaceprint("LokeshGupta38".isalpha())#False-包含numbers6.14.isdecimal()如果所有字符都是小数(0-9),则返回代码。否则返回False。Stringisdecimal()print("LokeshGupta".isdecimal())#Falseprint("12345".isdecimal())#Trueprint("123.45".isdecimal())#False-包含'point'print("12345678".isdecimal())#False-包含space6.15。isdigit()如果所有字符都是数字则返回真,否则返回假。指数也被认为是数字。Stringisdigit()print("LokeshGupta".isdigit())#Falseprint("12345".isdigit())#Trueprint("123.45".isdigit())#False-包含小数点print("1234\u00B2".isdigit())#True-26.16方块的unicode。isidentifier()如果字符串是有效标识符,则返回True,否则返回False。有效标识符仅包含字母数字字母(a-z)和(0-9)或下划线(_)。它不能以数字开头或包含任何空格。Stringisidentifier()print("Lokesh_Gupta_38".isidentifier())#Trueprint("38_Lokesh_Gupta".isidentifier())#False-从数字开始print("_Lokesh_Gupta".isidentifier())#Trueprint("38"Guptaisidentifier())#False-包含空格6.17。islower()如果所有字符都是小写,则返回True,否则返回False。不检查数字、符号和空格,只检查字母字符。Stringislower()print("LokeshGupta".islower())#Falseprint("lokeshgupta".islower())#Trueprint("lokesh_gupta".islower())#Trueprint("lokesh_gupta_38".islower())#True6.18.isnumeric()如果所有字符都是数字(0-9)则为真,it方法返回,否则返回假。指数也被视为数值。Stringisnumeric()print("LokeshGupta".isnumeric())#Falseprint("12345".isnumeric())#Trueprint("123.45".isnumeric())#False-包含小数点print("1234\u00B2".isnumeric())#True-方块26.19的unicode。isprintable()如果打印了所有字符,则返回True,否则返回False。不可打印字符用于表示某些格式化操作,例如:空白(被认为是不可见图形)回车制表符换行符分页符空字符串isprintable()print("LokeshGupta".isprintable())#Trueprint("LokeshGupta".isprintable())#Trueprint("Lokesh\tGupta".isprintable())#False6.20。isspace()如果字符串中的所有字符都是空格则返回真,否则返回假。6.21。istitle()如果文本的所有单词都以大写字母开头,其余单词均为小写,即标题大写,则返回True。否则为假。Stringistitle()print("LokeshGupta".istitle())#Trueprint("Lokeshgupta".istitle())#False6.22。isupper()如果所有字符都是大写,则返回True,否则返回False。不检查数字、符号和空格,只检查字母字符。Stringisupper()print("LOKESHGUPTA".isupper())#Trueprint("LOKESHGUPTA".isupper())#Trueprint("LokeshGupta".isupper())#False6.23.join()它可以迭代获取所有项目并使用强制指定的定界符将它们连接成一个字符串。Stringjoin()myTuple=("Lokesh","Gupta","38")x="#".join(myTuple)print(x)#Lokesh#Gupta#386.24.ljust()这个方法会使用指定的字符(默认为空格)作为左对齐字符串的填充字符。stringljust()txt="lokesh"x=txt.ljust(20,"-")print(x)#lokesh------------6.25.lower()它返回一个字符串,所有字符都是小写的。忽略符号和数字。stringlower()txt="LokeshGupta"x=txt.lower()print(x)#lokeshgupta6.26.lstrip()删除所有前导字符(默认为空格)。stringlstrip()txt="#LokeshGupta"x=txt.lstrip("#_,.")print(x)#LokeshGupta6.27.maketrans()为它的翻译/替换对创建一个字符映射。当在translate()方法中使用时,此翻译映射随后用于将字符替换为其映射的字符。stringmaketrans()dict={"a":"123","b":"456","c":"789"}string="abc"print(string.maketrans(dict))#{97:'123',98:'456',99:'789'}6.28.partition()它在给定文本中搜索指定字符串并将该字符串拆分为包含三个元素的元组:第一个元素包含指定字符串之前的部分。第二个元素包含指定的字符串。第三个元素包含字符串后面的部分。stringpartition()txt="mynameislokeshgupta"x=txt.partition("lokesh")print(x)#('mynameis','lokesh','gupta')print(x[0])复制代码#mynameisprint(x[1])#lokeshprint(x[2])#gupta6.29.replace()它将指定的短语替换为另一个指定的短语。它有两种形式:string.replace(oldvalue,newvalue)string.replace(oldvalue,newvalue,count)–“count”指定要替换的次数。默认为所有事件。Stringreplace()txt="AAAAA"x=txt.replace("A","B")print(x)#BBBBBx=txt.replace("A","B",2)print(x)#BBAAA6.30。rfind()它找到指定值的最后一次出现。如果在给定文本中找不到该值,则返回-1。Stringrfind()txt="mynameislokeshgupta"x=txt.rfind("lokesh")print(x)#11x=txt.rfind("amit")print(x)#-16.31.rindex()它查找指定值的最后一次出现,如果未找到该值则引发异常。Stringrindex()txt="mynameislokeshgupta"x=txt.rindex("lokesh")print(x)#11x=txt.rindex("amit")#ValueError:未找到子串6.32.rjust()将使用指定字符(默认为空格)作为填充字符右对齐字符串。stringrjust()txt="lokesh"x=txt.rjust(20,"#")print(x,"ismyname")################lokesh是我的name6.33.rpartition()它搜索指定字符串的最后一次出现并将该字符串拆分为包含三个元素的元组。第一个元素包含指定字符串之前的部分。第二个元素包含指定的字符串。第三个元素包含字符串后面的部分。stringrpartition()txt="我的名字是lokeshgupta"x=txt.rpartition("lokesh")print(x)#('我的名字是','lokesh','gupta')print(x[0])#mynameisprint(x[1])#lokeshprint(x[2])#gupta6.34.rsplit()它从右边开始将字符串拆分成一个列表。stringrsplit()txt="apple,banana,cherry"x=txt.rsplit(",")print(x)#['apple','banana','cherry']6.35.rstrip()它删除所有尾随字符(字符串末尾的字符),空格是默认的尾随字符。字符串rstrip()txt="lokesh"x=txt。rstrip()print(x)#'lokesh'6.36.split()它将字符串拆分成一个列表。您可以指定分隔符。默认分隔符是空格。Stringsplit()txt="mynameislokesh"x=txt.split()print(x)#['my','name','is','lokesh']6.37.splitlines()传入换行符,将字符串拆分成列表。stringsplitlines()txt="myname\nislokesh"x=txt.splitlines()print(x)#['myname','islokesh']6.38.startswith()如果字符串以指定值开头,则返回True,否则返回False。字符串比较区分大小写。stringstartswith()txt="mynameislokesh"print(txt.startswith("my"))#Trueprint(txt.startswith("My"))#False6.39.strip()它将删除所有前导(前导空格)和尾随(尾随空格)字符(默认为空格)。stringstrip()txt="mynameislokesh"print(txt.strip())#'mynameislokesh'6.40.swapcase()返回一个字符串,其中所有大写字母均为小写,反之亦然当然。stringswapcase()txt="MyNameIsLokeshGupta"print(txt.swapcase())#mYnAMEiSlOKESHgUPTA6.41.title()返回一个字符串,其中每个单词的第一个字符都是大写的。如果单词以数字或符号开头,则其后的第一个字母将被转换为大写。Stringtitle()print("lokeshgupta".title())#LokeshGuptaprint("38lokeshgupta".title())#38LokeshGuptaprint("1.lokeshgupta".title())#LokeshGupta6.42。translate()它需要翻译表根据映射表替换/翻译给定字符串中的字符。Stringtranslate()translation={97:None,98:None,99:105}string="abcdef"print(string.translate(translation))#idef6.43.upper()它返回一个字符串,其中所有字符都是全部大写。忽略符号和数字。stringupper()txt="lokeshgupta"print(txt.upper())#LOKESHGUPTA6.44.zfill()在字符串的开头添加零(0)直到达到指定长度。Stringzfill()txt="100"x=txt.zfill(10)print(0000000100)#0000000100学习愉快!作者:分布式编程来源:https://zthinker.com/如果您喜欢本文,请长按二维码关注分布式编程。