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

Python字符串常用操作TOP40

时间:2023-03-26 17:24:31 Python

文章第一篇公众号:CoderMrWu,每周分享优质技术文章和经验,欢迎大家关注,一起交流。今天看了一篇文章,总结了PythonString类型的40种常用语法。我觉得很有趣。我重新整理了翻译,分享给大家。尽管您可能不会使用某些语法,但掌握它仍然是一项很棒的技能。1/创建字符串s1='Thisisatest.'2/使用print语句查看输出#python3/python2>>>print('thisisatest.')thisisatest.#python3/python2>>>print('test')test#python2>>>print'123'1233/单行视图输出>>>s1='thisis'>>>s2='atest'>>>print(s1+s2)thisisatest4/singlelinenviewoutput>>>>print(s1+'\n'+s2)thisisatest5/stringsubscriptnotation>>>print(s1[0])t>>>print(s1[1])h>>>print(s1[8])Traceback(最近调用last):文件“”,第1行,在IndexError:stringindexoutofrange6/subscriptstringaddition>>>>print(s1[1]+s1[3]+s1[4])hs7/slicestring>>>print(s1[0:5])this>>>print(s1[0:])thisis>>>print(s1[:])thisis>>>print(s1[:-1])thisi>>>print(s1[::2])tis8/负索引切片>>>print(s1[-5:-1])isi>>>print(s1[-1::-1])#反转字符串sisiht9/%格式化操作符>>>print('thisisa%s'%'test')thisisatest>>>print('thisisa%(test)s'%{'test':'12345'})thisisa1234510/带整数的%>>>print('1+1=%(num)01d'%{'num':2})1+1=2>>>print('1+1=%(num)02d'%{'num':2})1+1=02>>>print('1+1=%(num)03d'%{'num':2})1+1=00211/%用于站位>>>print('%(a)s%(n)03d-程序是最好的。'%{'a':'Python','n':3})Python003-programisthebest.12/利用\n拆分字符串>>>print('%(a)s%(n)03d-program是最好的\n%(a)shelpedmeunderstandprogramming.'%{"a":"Python","n":3})Python003-programisthebestPythonhelpedmeunderstandingprogramming.13/多个\n>>>print('我喜欢%(a)s。\n我喜欢%(b)s。\n我喜欢%(c)s。\n我的%(d)s是%(num)03d.'%{"a":"tocode","b":"ice-cream","c":"travel","d":"age","num":32})我喜欢编码.Ilikeice-cream.Iliketotravel.myageis032.14/其他方式使用%>>>print('HelloeveryoneIamusingPython%d.7version.'%3.7)HelloeveryoneIamusingPython3.7版本。>>>打印('%s%s%d%d%f%f'%('Hercules','Zeus',100,20,3.2,1))HerculesZeus100203.2000001.000000>>>print('这是一个+%d整数'%10)这是一个+10的整数>>>print('这是一个-%d的负整数'%250)这是一个-250的负整数>>>print('这是一个混淆的-%d整数'%300)这是一个混淆-300integer15/Convertstringtointeger>>>s3='123'>>>print(10*int(s3))#乘法1230>>>print(10*s3)#乘法123123123123123123123123123123>>>print('1'+'45')145>>>print('1'+45)Traceback(最后一次调用):文件“”,第1行,在TypeError中:只能连接str(not"int")tostr>>>print(float('1')+float('45'))46.016/获取单个字符在字符串中出现的次数>>>text='thisisatest.'>>>print(text.count('t'))3>>>print(text.count('is'))217/将字符串改为大写>>>text='thisisatest.'>>>print(text.upper())THISISATEST.18/将字符串更改为小写>>>text='这是一个测试。'>>>print(text.upper())thisisatest.19/combinedstring>>>''.join(text)'hisisatest.'>>>','.join(['hello','Dean'])'你好,Dean'20/splitstring>>>text='thisisatest.'>>>print(text.split(''))['this','is','a','test.']21/判断字符串是否为大写>>>text'thisisatest.'>>>up_text=text.upper()>>>print(up_text.isupper())True22/判断字符串是否为小写>>>low_text=text.lower()>>>print(low_text.islower())True23/判断字符串是否有字母数字组成>>>text1='Lession01'>>>print(text1.isalnum())False>>>text2='Lession01'>>>print(text2.isalnum())True24/获取字符串的长度>>>text'thisisatest.'>>>print(len(text))1525/将字符串转为十进制ascii码>>>print(ord('A'))65>>>print(ord('B'))66>>>print(ord('a'))97>>>print(ord('b'))9826/将十进制asscii码转成字符串>>>打印(chr(65))A>>>print(chr(42))*>>>print(chr(118))v>>>print(chr(60))<27/转义符>>>print('怎么了?')这是怎么回事?>>>#在这种情况下不需要撇号。>>>print("怎么了?")怎么了?>>>#需要在引号上加上撇号>>>print("\"What'sup?\"")"What'sup?">>>#三重引号可以转义单引号、双引号和a更多。>>>print("""怎么了?""需要转义吗?"")怎么了?""需要转义吗?28/使用逗号格式化字符串>>>print('here',10,'apples')hereare10apples29/formatformatstring>>>text'thisisatest.'>>>print('Thisisa{}'.format(text))Thisisa这是一个测试。>>>print('Number{1}andnumber{0}'.format(100,200))#keywordpositionNumber200andnumber10030/格式按名称传递字符>>>print('Thereare{num}{type}'.format(num=10,type='apple'))这里有10个苹果。>>>tmp={'num':10,'type':'apple'}>>>print('这里有{num}个{type}.'.format(**tmp))有10个苹果这里。31/format中,字符按照参数顺序传递>>>print('这里有{1}{0}.'.format('Apple',10))这里有10个苹果。32/以格式访问对象属性>>>classRectangle:def__init__(self,length,width):self.length=lengthself.width=widthdef__str__(self):return'Rectangle({self.length},{self.width})'.format(self=self)>>>rect=Rectangle(10,5.5)>>>print(rect.__str__())Rectangle(10,5.5)33/对齐文本>>>print('{:<10}'.format('X'))#左对齐X>>>print('{:>10}'.format('X'))#右对齐X>>>print('{:^10}'.format('X'))#centerX>>>print('{:?^10}'.format('X'))#添加一个填充字符????X?????34/format二进制、八进制和十六进制>>>print('二进制数:{0:b}'.format(50))二进制数:110010>>>print('八进制数:{0:o}'.format(100))Octalnumber:144>>>print('Hexadecimalnumber:{0:x}'.format(2555))Hexadecimalnumber:9fb35/usecommaasdelimiter>>>print('{:,}'.format(2783727282727))2,783,727,282,727>>>print('{:.2%}'.format(90.60/100))90.60%36/使用f格式化字符串>>&g吨;item_1,item_2,item_3='computer','mouse','browser'>>>print(f"他用了{item_1}。")他用了电脑。>>>print(f"他用了{item_2}和{item_3}。")他使用鼠标和浏览器。>>>print(f"他每天使用{item_1}3次。")他每天使用电脑3次。37/使用模板格式化字符串#docs:https://docs.python.org/3/library/string.html#template-strings>>>fromstringimportTemplate>>>poem=Template('$xareredand$y是蓝色的')>>>print(poem.substitute(x='roses',y='violets'))玫瑰是红色的,紫罗兰是蓝色的38/字串的遍历>>>text'这是一个测试。'>>>foritemintext:...print(item)...thisisatest.39/使用while循环>>>i=0>>>whilei>>deftriple_quote_docs():"""在落日的金色闪电中,在乌云闪耀的天空中,你漂浮着奔跑着,就像一种无形的快乐,它的比赛才刚刚开始。"""return>>>print(triple_quote_docs.__doc__)在沉没的太阳的金色闪电中,在云彩明亮的上方,你漂浮着奔跑着,就像一场刚刚开始的无实体的欢乐。>>>参考:https://pysnakeblog.blogspot.com/2019/09/top-40-python-string-processing-in.html