python 字串特點

來源:互聯網
上載者:User

除了數值,Python可以操作字串,它可以表現在以下幾個方面。包含在單引號或雙引號:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

字串可以寫多行。可以用\n表示,下一行是一個合乎邏輯的延續行,最後一個字元用反斜線:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
   Note that whitespace at the beginning of the line is\
significant."

print hello

字串可以被包圍在一對三重引號裡面:

print """
Usage: thingy [OPTIONS]
    -h                        Display this usage message
    -H hostname               Hostname to connect to
"""

字串可以被串連在一起,用“+”運算子,重複*:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

兩個彼此相鄰的字串文字自動連接:

>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
 File "<stdin>", line 1, in ?
   'str'.strip() 'ing'
                     ^
SyntaxError: invalid syntax

注意:word字串的內容是: “HelpA”  可以是下標(索引)和C一樣,字串的第一個字元下標(索引)0。可以指定的子串切片標誌來表示:兩個指數由冒號分隔。

>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

切片索引可以使用預設值;前一個索引預設為零,第二個索引預設被切片的字串的大小。

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'

和C字串不同,Python字串不能改變。想修改指定索引位置的字串會導致錯誤:

>>> word[0] = 'x'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment

然而,建立一個新的字串是簡單而有效:

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

這裡是一個有用的切片操作:[:]+[:]等於。

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

指數可以是負數,從右邊開始計數。例如:

>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # Everything except the last two characters
'Hel'
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.