標籤:
在2.7中 如果使用中文 需要在最開始使用#coding=utf-8才能夠運行
#已知字串 s = "i,am,lilei",請用兩種辦法取出之間的“am”字元。
import strings = "i,am,lilei"s1=s.split(‘,‘)#分割結果是listprint s[2:4]print s1[1]print s[1,1,2]#開始 結束 步進(集合也適用)
可以通過在其他對象中添加list或者dict來變相解決例如tuple等不能變的問題
字串拼接:
print "%s%s" % (‘a‘,‘b‘)print "{a} {b}".format(a=‘a‘,b=‘b‘)#字串較多時 建議用這種(使用format是無序的) print a,b print a+b
常用 字串工具可以在字串的方法中找 例如replace(替換),isupper(是否大寫),islower(是否小寫),swapcase(大小寫轉換),len(長度)等等
sort()是對傳入的元素進行排序
sorted(0是返回排序之後的元素
需要插入\ 之類的特殊符號時候 需要在前面加一個\
print \\ #\print \n #分行符號
下面是一些字串相關的練習題
#定義一個方法func,該func可以引入任意多的字串參數,#結果返回(長度)最長的字串def func2(*input_str): longest_str=‘‘ for x in input_str: if isinstance(x, str): if len(x) > len(longest_str): longest_str=x else: print x,‘is not str type value‘ return longest_strprint func2(‘asdasd‘,‘zxczxc‘,‘12343rfdgrdqweqwe‘,‘123‘)
#統計該文檔中,"be" "is" "than" 的出現次數str1=‘‘‘The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren‘t special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you‘re Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it‘s a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let‘s do more of those!‘‘‘str2=str1.split(‘ ‘)#返回list 然後對list 遍曆num1=0num2=0num3=0for x in str2: temp=x.strip() if temp == ‘be‘: num1=num1+1 elif temp == ‘is‘: nm2=num2+1 elif temp == ‘than‘: num3=num3+1print num1,num2,num3
Python 學習筆記 字串