# 每天學點Python之strings
在Python3中所有的字符編碼都是Unicode,所以不用再擔心編碼問題了。
### 基本操作
在Python中字符串可以用單引號或者雙引號中包含字符來表示,下面列一下最最基本的操作,分別是賦值、求長度、特定位置的字符和字符串連接:
~~~
In[5]: s = "hello world"
In[6]: len(s)
Out[6]: 11
In[7]: s[0]
Out[7]: 'h'
In[8]: s + '!'
Out[8]: 'hello world!'
~~~
如果字符串很長,要跨越多行,可以用三引號將內容包含進來:
~~~
In[32]: s = '''a
... b
... c
... '''
In[33]: s
Out[33]: 'a\nb\nc\n'
~~~
> 注:命令前的In/Out[n]只是表示第幾條命令,沒有實際意義
### 格式化
Python的字符串格式化非常簡單,在需要插入值的地方用{n}表示,直接調用format()函數并傳入相應的參數即可,注意下標是從0開始的,而且傳入的參數必須大于等于需要的參數數目(多傳入的會被忽略):
~~~
In[10]: s = 'my name is {0}, my age is {1}'
In[11]: s.format('drfish',20)
Out[11]: 'my name is drfish, my age is 20'
In[12]: s.format('drfish')
Traceback (most recent call last):
File "<ipython-input-12-305d7c657a14>", line 1, in <module>
s.format('drfish')
IndexError: tuple index out of range
In[13]: s.format('drfish',20,22)
Out[13]: 'my name is drfish, my age is 20'
~~~
如果參數非常多,用數字來表示容易產生混亂,可以使用別名表示:
~~~
In[28]: '{name} is {age}. '.format(name="drfish", age=22)
Out[28]: 'drfish is 22. '
~~~
再來看復雜一點的,輸如的參數不僅僅是簡單的值替換,而能在字符串中對其進行后續處理,如傳入一個字典,可以對其取某個鍵的值,同理還可以使用一些復雜的對象的方法屬性:
~~~
In[22]: s = 'my name is {0[name]}, my age is {0[age]}'
In[23]: s.format({"name":"drfish","age":20})
Out[23]: 'my name is drfish, my age is 20'
~~~
此外還能對輸出的格式進行規定:
~~~
# 保留小數點后4位
In[26]: '{0:.4} is a decimal. '.format(1/3)
Out[26]: '0.3333 is a decimal. '
# 用'_'補齊字符串
In[27]: '{0:_^11} is a 11 length. '.format("drfish")
Out[27]: '__drfish___ is a 11 length. '
# 指定寬度
In[30]: 'My name is {0:8}.'.format('drfish')
Out[30]: 'My name is drfish .'
~~~
### 常用方法
**大小寫**
字符串可以直接進行大小寫的判斷與轉換:
~~~
In[34]: 'hello'.upper()
Out[34]: 'HELLO'
In[35]: 'Hello'.lower()
Out[35]: 'hello'
In[36]: 'Hello'.isupper()
Out[36]: False
~~~
**分割**
分割函數str.split()可以接收兩個參數,一個是分割符,另一個是進行分割的數目:
~~~
In[37]: 'a=1,b=2,c=3'.split('=',2)
Out[37]: ['a', '1,b', '2,c=3']
~~~
**計數**
統計一個字符串中的某字符串的數目:
~~~
In[38]: "ab c ab".count("ab")
Out[38]: 2
~~~
**截取**
截取操作與列表相同:
~~~
In[39]: "hello world"[3:8]
Out[39]: 'lo wo'
~~~