字符串是python中常用到的數據類型,總結了如下部分常用到的對字符串的操作。
len(s)
返回字符串的長度
s[2]
通過索引獲取字符串中的第3個字符
s[1:5]
返回第2個到第5個字符的子字符串。注意字符串切片前面是半區間,後面是開區間。並且索引是由0開始的
s[:5]
返回第1個到第5個字符的子字符串。如果中括號內省略寫分號:前的值,則表示從第一個字符開始
s[1:]
返回第2個到最後一個字符的子字符串。如果中括號內省略寫分號:後的值,則表示到最後一個字符爲止
+
可連結2個字符串
in
如果字符串中包含給定的字符返回True
not in
如果字符串中不包含給定的字符返回True
s.find()
返回字符串開始的索引值,否則返回-1
相關方法:rfind,index,rindex,count,startwith,endwith
s.rfind()
返回字符串最後一次出現的位置,如果沒有匹配項則返回-1
s.isdigit()
如果 s只包含數字則返回 True 否則返回 False.
s.lower()
轉換 s中所有大寫字符爲小寫.
相關方法:islower, capitalize, swapcase, title, istitle, upper, isupper
str()
轉換成字符串
split()
它是join的逆方法,用來將字符串分割成序列。
>>> '1+2+3+4+5'.split('+')
['1','2','3','4','5']
>>> '/usr/bin/env'.split('/')
['','usr','bin','env']
strip
strip方法返回去除兩側(不包括內部)空格的字符串。
string.encode(encoding=’UTF-8’, errors=’strict’)
以 encoding 指定的編碼格式編碼 string,如果出錯默認報一個ValueError 的異常,除非 errors 指定的是’ignore’或者’replace’
string.decode(encoding=’UTF-8’, errors=’strict’)
以 encoding 指定的編碼格式解碼 string,如果出錯默認報一個 ValueError 的 異 常 , 除 非 errors 指 定 的 是 ‘ignore’ 或 者’replace’
示例:
#coding:utf8
import os
strDir = "D:\\臨時共享"
strName = "brand-file-name-2.7.124.124-full.45bb09bdf44d7b117dc507ad2e33ckd8.exe"
strLen = len(strName) # 獲得字符串的長度等於69
print "The length is " + str(strLen)
print "strName[0]=" + strName[0] # 輸出第1個字符 'b'
print "strName[3]=" + strName[3] # 輸出第4個字符 'n'
print "strName[1:5]=" + strName[1:5] # 輸出第2-5個字符 ‘rand’
print "strName[:5]=" + strName[:5] # 輸出第0-5個字符 'brand'
print "strName[67:]=" + strName[66:] # 輸出第67-69個字符 'exe'
print strName[0] + strName[66:] # 輸出字符 'bexe'
if "exe" in strName: # 判斷 'exe'是否在字符串中
print "'exe' is in " + strName
fullIndex = strName.find("full") # 獲得子串‘full'所在的位置
print "The string before 'full' is " + strName[:fullIndex] # 輸出 'brand-file-name-2.7.124.124-'
exeIndex = strName.rfind(".") # 獲得最後一個'.'所在的位置
print "The format is " + strName[exeIndex+1:]
# 獲得字符串中第一個數字
print "The first Num is " + filter(str.isdigit,strName)[0]
#識別中文編碼路徑
strFileName = os.path.join(strDir.decode('utf8').encode('cp936'),strName)
print strFileName
以上示例執行結果:
The length is 69
strName[0]=b
strName[3]=n
strName[1:5]=rand
strName[:5]=brand
strName[67:]=exe
bexe
'exe' is in brand-file-name-2.7.124.124-full.45bb09bdf44d7b117dc507ad2e33ckd8.exe
The string before 'full' is brand-file-name-2.7.124.124-
The format is exe
The first Num is 2
D:\��ʱ����\brand-file-name-2.7.124.124-full.45bb09bdf44d7b117dc507ad2e33ckd8.exe
在編譯器下輸出中文路徑顯示還是亂碼,但是不影響使用,如os.listdir(strDir.decode(‘utf8’).encode(‘cp936’))還是可以識別到路徑並列出文件夾下的文件名稱的。