Python 之字串常用操作
阿新 • • 發佈:2018-12-09
字串表示:str與repr的區別
str()函式把值轉換為合理形式的字串,便於理解
repr()函式是建立一個字串,以合法的Python表示式形式來表示值。
如下:
#-*-encoding:utf-8-*- print repr("hello repr") print str("hello str") 執行結果: 'hello repr' hello str 字串格式化: 字串格式化轉換型別 轉換型別 含義 d ,i 帶符號的十進位制整數 o 不帶符號的八進位制 u 不帶符號的十進位制 x 不帶符號的十六進位制(小寫) X 不帶符號的十六進位制(大寫) e 科學計數法表示的浮點數(小寫) E 科學計數法表示的浮點數(大寫) f ,F 十進位制浮點數 C 單字元(接受整數或單字元字串) r 字串(使用repr轉換任意python物件) s 字串(使用str轉換任意python物件) 例如: commodity="name : %s ,price:%s" %("蘋果","12.86") print commodity 執行結果: name : 蘋果 ,price:12.86 [Finished in 0.2s] 字串常用方法: 1.1 find() 1.2 join() 1.3 lower() 1.4 replace() 1.5 split() 1.6 strip() find()方法,用於在一個比較長的字串中查詢子串,它返回第一個子串所在的索引,如果沒有找到則返回-1。 str_a="Hello, welcome to the Python world!" print str_a.find("o") #列印第一次出現o字元的索引位置 執行結果: 4 [Finished in 0.2s] join()方法,用於連線序列中的元素。(與split方法功能相反) url=["d:","program Files","python"] print "\\".join(url) #使用\符號將列表連線成一個字串 執行結果: d:\program Files\python [Finished in 0.2s] lower()方法,用於將字串轉化為小寫字母 str_a="ABCdef" print str_a.lower() #將全部字元轉化為小寫字元 執行結果: abcdef [Finished in 0.3s] replace()方法,用於將字串中所有匹配項都替換成新的字串。 str_a="Hello, welcome to the Python world!" print str_a.replace("to","AAA") #將字串中的o字元,全部替換為AAA,並把替換後結果返回 print str_a 執行結果: Hello, welcome AAA the Python world! AAA Hello, welcome to the Python world! to [Finished in 0.2s] split()方法,用於將字串根據特定字元進行分隔成列表。 URL="d:\\program Files\\python" new_list=URL.split("\\") #根據出現\\的位置,進行分隔 print new_list 執行結果: ['d:', 'program Files', 'python'] [Finished in 0.2s] strip()方法,用於去除字串兩側(不包含內容)空格的字串。 str_a=" hello ,everyone! " print str_a print str_a.strip(" ") #去除左右兩邊的空格 執行結果: hello ,everyone! hello ,everyone! [Finished in 0.3s]