1。字符串反转字符串反转的方法有很多种,这里介绍两种:一种是切片,一种是python字符串反转的方法。#-!-coding:utf-8-!-string='helloworld'#方法1new_str=string[::-1]ic(new_str)#方法2new_str2=''.join(reversed(string))ic(new_str2)'''ic|new_str:'dlrowolleh'ic|new_str2:'dlrowolleh''''2。首字母大写这里我们也介绍两种方法,不同的是**capitalize()**只将首字母大写**title()**是每个单词开头的首字母大写#首字母大写string='hellopythonandworld'#方法一new_str=string.capitalize()ic(new_str)#方法二new_str2=string.title()ic(new_str2)'''ic|new_str:'HelloPythonandworld'ic|new_str2:'HelloPythonAndWorld''''3。查询唯一元素我们利用set的唯一性来判断字符串的唯一元素:string='hellohellohello'new_str=set(string)#settypeic(new_str)#stringtypenew_str=''.join(new_str)ic(new_str)'''ic|new_str:{'l','o','h','e'}ic|new_str:'lohe''''4.变量交换python中的变量交换比java简单很多。不需要定义第三个中间变量来交换两个变量,直接交换即可实现。a='hello'b='world'ic(a+b)#直接交换两个变量a,b=b,aic(a+b)'''ic|a+b:'helloworld'ic|a+b:'worldhello''''5。列表排序列表排序这里我们也提供了两种方式。首先是列表自带的**sort()方法;第二个是python内置函数sorted()**方法。score=[88,99,91,85,94,85,94,78,100,80]#方法一new_score=sorted(score)ic('默认升序:',new_score)score=[57,29,11,27,84,34,87,25,70,60]#方法2new_score2=sorted(score,reverse=True)ic('设置降序',new_score2)'''ic|'默认升序:',new_score:[78,80,85,85,88,91,94,94,99,100]ic|'设置降序',new_score2:[87,84,70,60,57,34,29,27,25,11]'''6.列表推导使用列表推导,可以快速生成列表或者根据列表生成满足需求的列表。#生成10-100个数字内的10个随机整数=[random.randint(10,100)forxinrange(10)]ic(numbers)#输入50折后的价格price=[800,500,400,860,780,520,560]half_price=[(x*0.5)forxinprice]ic(half_price)'''ic|numbers:[64,22,80,70,34,81,74,35,85,12]ic|half_price:[400.0,250.0,200.0,430.0,390.0,260.0,280.0]'''7。Mergestrings合并字符串我们使用string的.join()方法来实现。lists=['hello','world','python','java','c++']#mergestringnew_str=''.join(lists)ic(new_str)'''ic|new_str:'helloworldpythonjavac++''''8。拆分字符串我们使用string的split()方法来拆分字符串。string='helloworldpythonjavac++'string2='hello|world|python|java|c++'#拆分字符串new_str=string.split('')ic(new_str)new_str2=string2.split('|')ic(new_str2)'''ic|new_str:['hello','world','python','java','c++']ic|new_str2:['hello','world','python','java','c++']'''9。回文串检测回文串是指aba、abba、cccbccc、aaaa等对称的字符串。我们可以根据前面提到的切片来检测这个特殊的字符串序列。str='20211202'ifstr==str[::-1]:print('yes')else:print('no')'''yes'''10.统计列表中元素出现的次数统计列表中每个元素出现的次数我们使用集合的Counter方法的次数。fromcollectionsimportCounterlists=['a','a','b','b','b','c','d','d','d','d','d']#统计所有元素出现的次数counts=Counter(lists)ic(counts)#统计元素出现的次数ic(counts['d'])#统计出现次数最多的元素ic(counts.most_common(1))'''ic|counts:Counter({'d':5,'b':3,'a':2,'c':1})ic|counts['d']:5ic|counts。most_common(1):[('d',5)]'''
