Python字符串

1)在python中,可以用單引號(’ ’)或者雙引號(“ ”)來表示字符串,效果都是一樣的,可以用‘/’來進行特殊字符的轉義。

 

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

2)如果字符前面 \ 解釋特殊字符可以通過在第一個引號前面加上r來表示的原始字符串。

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name

3)字符串可以多個種方法使用三重引號:"""......""" ' '...' '

>>>print("""

Usage: thingy[OPTIONS]

     -h                        Display this usagemessage

     -H hostname               Hostname to connect to

""")

 

Usage: thingy[OPTIONS]

     -h                        Display this usagemessage

     -H hostname               Hostname to connect to

(4)可以通過在字符串的行尾加上“/”來使兩行變成一行。

>>>print("""

Usage: thingy[OPTIONS]\

     -h                        Display this usagemessage

     -H hostname               Hostname to connect to

""")

 

Usage: thingy[OPTIONS]     -h                        Display this usagemessage

     -H hostname               Hostname to connect to

5可以連接字符串(粘結在一起)+ 運算符,複製使用 *:

>>>print(3 * 'un' + 'ium')

Unununium

(6)兩個或多個字符串(即封閉引號之間的字符串)緊鄰的將自動連接。

>>> 'Py' 'thon'
'Python'

但是,這僅僅適用於字符串文本之間,不適用於變量以及表達式。

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax

如果想要連接變量和字符串文本,需要使用+

>>> prefix + 'thon'
'Python'

當你想要打破長字符串時,此功能是特別有用的︰

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

(7)字符串可以索引 (下標),第一個字符的下標爲0Python中沒有單獨字符類型;字符大小爲 1 字符串

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

索引可以負數右邊開始計數,從-1開始︰

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'
注意:當索引超出字符串大小時,會報錯。
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
 
(8)除了索引,還支持切片。索引用來獲取單個字符,切片允許您獲取子字符串︰
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
可以看出,切片中,開始的位置被包括,而結束的位置不包含。這樣,
s[:i]+s[i:]永遠等於s:
 
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
 
切片指數具有有用的默認值;省略的第一個索引默認爲零,省略第二個索引默認爲被切成字符串的大小。
>>> word[:2]   # 從0到2的字符
'Py'
>>> word[4:]   # 從4到結尾的字符
'on'
>>> word[-2:]  #從-2到結尾的字符
'on'
 
不同於索引超出會報錯,切片不一定會報錯:
>>> word[4:42]
'on'
>>> word[42:]
''
但是,負數索引超出的時候,切片會報錯:
>>> print(word[-10,3])
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    print(word[-10,3])
TypeError: string indices must be integers
 
(9)python中字符串是不可變的,所以不能使用索引或者切片對字符串進行改變。
>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment
如果你需要一個新字符串,你需要重新建一個字符串
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
(10)內建函數len()返回字符串的長度
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
 
當然,字符串還有很多其他的性質和方法,以後會繼續講解。
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章