Python字符串方法

split()

將字符串分割成列表,默認以空格爲分隔符python

a="you can't see mee"
a.split()             #輸出內容爲 ["you","can't","see","me"]
a.split(" ' ")        #輸出內容爲['you cant','t see me']

join()

鏈接字符串數組,用符號鏈接字符串,可將 列表,字典,元組轉換成字符串數組

注意:列表,元組等序列裏面的內容必須是字符串,不然會報錯函數

a="123"
" |".join(a)
>>'1 |2 |3'
b=['a','b','c']
" ".join(b)
>>'a b c'
c=('i','j','k')
"_".join(c)
>>'i_j_k'

###strip() 用於移除字符串兩端的字符 ;當括號爲空時候,默認刪除空白符(包括'\n', '\r', '\t', ' ')this

a="        123"
a.strip()                        #輸出內容爲 "123" ,注意前面有a=" 123"前面空格

例子2:指針

a= "0000000this is string example....wow!!!0000000"
print a.strip("0")

#以上實例輸出結果以下:
this is string example....wow!!!

特別說明: 只要刪除內容存在,不論順序正反都同樣 如strip("12") 和strip("21"),以下所示code

c="123acb"
c.strip("12")                #輸出內容爲"3abc"
c.strip("21")                #輸出內容同樣爲"3abc"

strip()總結:索引

python的strip函數有兩種用法:通常去首尾ip

  • 若是省略參數,那麼將會執行去除兩端空格。如:
str="   abc   "  
print(str.strip()) #結果爲abc
  • 若是傳入了參數,那麼將按照字符在兩端去除相應字符,但這時候和空格沒有任何關係。
str="  abc "  
print(str.strip(" a")) #輸出"bc"  
print(str.strip("ac")) #輸出" abc " 什麼都沒作  
print(str.strip("a")) #輸出" abc "什麼都沒作

find()

檢測字符串中是否包含子字符串 str 查找內容在第幾個字符,不存在返回**-1**字符串

a="you can't see me"
a.find("you")                 #輸出內容爲0
afind("can't")               #輸出內容爲4
a.find("asd")               #輸出內容爲-1

###index() 檢測字符串中是否包含子字符串 str
用法和find() 差很少,不過若是查找內容不存在,返回一個錯誤,若是指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內string

a="you can't see me"
a.index("you")            #輸出內容爲0
a.index("can't")          #輸出內容爲4
a.index("asd")           
# 輸出內容爲:
 Traceback (most recent call last):
  File "<stdin>", line 1,in <module>
ValueError: substring not found
```
若是參數出現不少次,要如何作呢?

例2:

```
 t=tuple('Allen')
print(t)
#輸出 ('A', 'l', 'l', 'e', 'n')
a=t.index('l',2)
print(a)
#輸出2
```
由於第一個’l’的出現位置是1,因此咱們將開始索引加1繼續尋找,果真,在索引爲2的位置又找到了’l’。

###seek()
seek()函數是屬於文件操做中的函數,用來移動文件讀取指針到指定位置。
語法:
```
fileObject.seek(offset[, whence])
#offset – 開始的偏移量,也就是表明須要移動偏移的字節數
#whence:可選,默認值爲 0。給offset參數一個定義,表示要從哪一個位置開始偏移;0表明從文件開頭開始

#算起,1表明從當前位置開始算起,2表明從文件末尾算起。
```
###upper()
大小寫轉換
```
s='abc'
s.upper()
#輸出ABC
```
###isalpha()
是否爲字母
```
>>>s.isalpha()
True
```
相關文章
相關標籤/搜索