1. 程式人生 > >Python 之字符串常用操作

Python 之字符串常用操作

連接 utf-8 welcome 轉換 如果 program The 新的 repl

字符串表示: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]

  

Python 之字符串常用操作