python中字符串的判断
这期内容当中小编将会给大家带来有关python中字符串的判断,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1、检查给定字符串是否是回文(Palindrome)
my_string="abcba"mifmy_string==my_string[::-1]:print("palindrome")else:print("notpalindrome")#Output#palindrome
2、列表的要素频率
有多种方式都可以完成这项任务,而我最喜欢用Python的Counter 类。Python计数器追踪每个要素的频率,Counter()反馈回一个字典,其中要素是键,频率是值。
也使用most_common()功能来获得列表中的most_frequent element。
#findingfrequencyofeachelementinalistfromcollectionsimportCountermy_list=['a','a','b','b','b','c','d','d','d','d','d']count=Counter(my_list)#definingacounterobjectprint(count)#Ofallelements#Counter({'d':5,'b':3,'a':2,'c':1})print(count['b'])#ofindividualelement#3print(count.most_common(1))#mostfrequentelement#[('d',5)]
3、查找两个字符串是否为anagrams
Counter类的一个有趣应用是查找anagrams。
anagrams指将不同的词或词语的字母重新排序而构成的新词或新词语。
如果两个字符串的counter对象相等,那它们就是anagrams。
FromcollectionsimportCounterstr_1,str_2,str_3="acbde","abced","abcda"cnt_1,cnt_2,cnt_3=Counter(str_1),Counter(str_2),Counter(str_3)ifcnt_1==cnt_2:print('1and2anagram')ifcnt_1==cnt_3:print('1and3anagram')
4、使用try-except-else块
通过使用try/except块,Python 中的错误处理得以轻松解决。在该块添加else语句可能会有用。当try块中无异常情况,则运行正常。
如果要运行某些程序,使用 finally,无需考虑异常情况。
a,b=1,0try:print(a/b)#exceptionraisedwhenbis0exceptZeroDivisionError:print("divisionbyzero")else:print("noexceptionsraised")finally:print("Runthisalways")
上述就是小编为大家分享的python中字符串的判断了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。