1. 程式人生 > >python基礎之字符串操作

python基礎之字符串操作

ike ali pan color span 替換 dex sta als

下面顯示代碼在ipython3中實現

s=i like python

#首字母大寫

capitalize()
1 In [3]: s=i like python
2 
3 In [4]: s.capitalize()
4 Out[4]: I like python

#全部轉換大寫,全部轉換小寫

upper() lower()

In [6]: s.upper()
Out[6]: I LIKE PYTHON

1 In [7]: s.lower()
2 Out[7]: i like python

#大寫轉換,將原來大寫的轉換成小寫,小寫轉換成大寫

In [8]: s.swapcase()
Out[
8]: I LIKE PYTHON

#單詞首字母大寫

In [9]: s.title()
Out[9]: I Like Python

#居中

In [11]: s.center(20) #默認是空格
Out[11]:    i like python    
In [14]: s.center(20,~)#制定字符串
Out[14]: ~~~i like python~~~~

s = ‘ i Like Pyhon ‘
#刪除前後空格(默認是刪除空格,可以指定要刪除的前後字符串)

strip
In [16]: s.strip()
Out[16]: i Like  Pyhon

#刪除後邊空格

rstrip
In [17]: s.rstrip()
Out[17]:   i Like  Pyhon

#刪除左邊空格

lstrip
In [18]: s.lstrip()
Out[18]: i Like  Pyhon  

#公共方法

#獲取字符串元素長度

len
In [19]: len(s)
Out[19]: 17

#查看元素是否以某字符串開頭(返回True,False),

startswith
endswith
In [20]: s.startswith( )
Out[20]: True

In [22]: s.endswith( )
Out[
22]: True

#根據元素找索引號(如果找不到則返回-1)

find

In [23]: s.find(i)
Out[23]: 2

index(如果找不到則會報錯)

In [26]: s.index(i)
Out[26]: 2

#統計( 如果統計不到元素則返回0)

count

In [29]: s.count(i)
Out[29]: 2

#替換

In [31]: s.replace(Like,love)
Out[31]:   i love  Pyhon  

python基礎之字符串操作