字符串任何語言的基本操作剩岳,學完可以大致了解一下語言的特色
- 創(chuàng)建字符串
字符串可以用單引號 ('...') 或雙引號 ("...") 標識
>>> 'hello world'
'hello world'
>>> "hello world"
'hello world'
>>>
——————————————
(\)可以用來轉義引號
>>> 'he says "hello world"'
'he says "hello world"'
>>> "he says \"hello world\""
'he says "hello world"'
>>>
——————————————
print()為輸出語句 #print和()之間空格可加可不加
>>> print ('he says \"hello world\"')
he says "hello world"
>>>
>>> s = "he says \"hello world\""
>>> print(s)
he says "hello world"
>>>
如果帶有 \ 的字符被當作特殊字符劳闹,可以使用 *原始字符串*,方法是在第一個引號前面加上一個 r
>>> print('ni\'hao\n')
ni'hao
>>> print(r'ni\'hao\n')
ni\'hao\n
>>>
字符串文本能夠分成多行。
一種方法是使用三引號:"""..."""或者 '''...'''。行尾換行符會被自動包含到字符串中鹿鳖,但是可以在行尾加上 \ 來避免這個行為。
>>> print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
將生成以下輸出(注意壮莹,沒有開始的第一行):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
>>>
-
字符串操作語句
‘+’
1.字符串可以由 + 操作符連接(粘到一起)翅帜,可以由 * 表示重復
>>> print(3*'ni'+'shi')
nininishi
>>> print(3*('ni'+'shi'))
nishinishinishi
'*'
2.* 只用于兩個字符串文本,不能用于字符串表達式
>>> s = 'ni'
>>> pirnt(3*s)
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
pirnt(3*s)
NameError: name 'pirnt' is not defined
‘+’使用注意事項
1.+可以用于兩個字符串文本
>>> n = 'shi'
>>> print(s+n)
nishi
>>> print(s,n)
ni shi>>> print(3*'ni'+'shi')
nininishi
>>> print(3*('ni'+'shi'))
nishinishinishi
>>> s = 'ni'
>>> pirnt(3*s)
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
pirnt(3*s)
NameError: name 'pirnt' is not defined
>>> n = 'shi'
>>> print(s+n)
nishi
>>> print(s,n)
ni shi
2.連接多個變量或者連接一個變量和一個字符串文本
>>> p = 'py'
>>> print(p + 'thon')
python
>>>
-
切分字符串
1. 索引
字符串也可以被截取(檢索)命满。
類似于 C 涝滴,字符串的第一個字符索引為 0 。
Python沒有單獨的字符類型胶台;一個字符就是一個簡單的長度為1的字符串歼疮。
>>> sentence = 'ni hao shi jie'
>>> sen = sentence
>>> sen[0]
'n'
>>> sen[10]
' '
索引也可以是負數(shù),這將導致從右邊開始計算诈唬。
>>> sen[-1]
'e'
2. 切片
索引用于獲得單個字符韩脏,切片 讓你獲得一個子字符串。
>>> sen[0:5]
'ni ha'
>>> sen[-1:0]
''
>>> sen[-1:3]
''
>>> sen[-1:-4]
''
>>> sen
'ni hao shi jie'
>>> sen[-4:-1]
' ji'
>>> sen[0:-1]
'ni hao shi ji'
>>> sen[1:-1]
'i hao shi ji'
>>>
注意铸磅,包含起始的字符赡矢,不包含末尾的字符。這使得 s[:i] + s[i:]永遠等于 s阅仔。
>>> sen[:2]+sen[2:]
'ni hao shi jie'
>>>
切片的索引有非常有用的默認值吹散;省略的第一個索引默認為零,省略的第二個索引默認為切片的字符串的大小八酒。
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
一個過大的索引值(即下標值大于字符串實際長度)將被字符串實際長度所代替空民;
當上邊界比下邊界大時(即切片左值大于右值)就返回空字符串。
字符串不可以被更改
3. 長度
內(nèi)置函數(shù)返回字符串長度羞迷。
>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34
4. 更多方法
Text Sequence Type — str
字符串是 序列類型 的例子界轩,它們支持這種類型共同的操作。
String Methods
字符串和Unicode字符串都支持大量的方法用于基本的轉換和查找闭树。
String Formatting
這里描述了使用 str.format() 進行字符串格式化的信息耸棒。
String Formatting Operations
這里描述了舊式的字符串格式化操作,它們在字符串和Unicode字符串是 %
操作符的左操作數(shù)時調(diào)用报辱。
-
遺留問題
1.更多的字符串方法