2017年6月10日 星期六

Python ê 基礎 -- 字串 (Strings)

(Strings)和數字仝款,是 Python 上基礎的資料型態。會使講,你頭一工使用 Python, 你就佇使用字串。m̄-koh,你無感覺niâ-niâ。每擺,你使用 print() 來印出結果的時陣,你就愛字串做伊的輸入。只是,有時就算你囥數字抑是 Lists,print() 會自動你轉換做字

字串的表示方式有幾落種:單引句點 'xxxxx', 抑是雙引句點 "xxxx" 攏會使得

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> "doesn't"  # ...or use double quotes instead
"doesn't"

你若用雙引句點單引句點就hőng當做是普通字元。倒反過來,用單引號,雙引句點就是普通字元。
你若欲用單引號來一咧內底有單引句點的字串,抑是雙引句點有雙引號的字串,就愛用倒斜線(\)。
\ 予人叫做逃走字元(Escape character),意思是伊會予後壁彼咧字元的意義改變。本底佇引號內的意義,踮頭前加一咧逃走字元了後,意思無仝。

>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "\"Yes,\" he said."
'"Yes," he said.'

踮頂懸,\ 予後壁的 ' 抑是 ", 失去引號的功能。而且,逃走字元嘛會予普通字元有特別的意思,比如講:

>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

n 本來是普通字元,m̄-koh加上逃走字元,\n 是換的意思。這咧轉換,佇 print() 才會作用

有時,你感覺用 \ 真歹看相,共字串花巴哩貓,看袂清原在的字串生做啥物,你會使ti̋字串進前加一字 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

閣有一種字串的表示,伊是用佇幾落的字串:

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

你就愛看斟酌:內底的 \ 無印--出來。彼 \ 是逝(你聽過啉酒有紲無?),意思是一逝佮下跤彼逝是相連紲的仝一逝。你若無加 \,就會加印一咧換逝 \n 佇頭前。你會使試看覓

咱會使用 + 共字串接--起來。用 * 來予字串重複幾落擺:

>>> 3 * 'dog' + 'cat'
'dogdogdogcat'

若是兩的,抑是的字串前後排--咧,嘛是自動共鬥做伙:

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

m̄-koh,這步袂使用佇變數共文字的字串:

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

字串嘛會使看做是 "字的 List"。你會使用 List 內底學著的手路,像 索引(Index)  :

>>> word = 'Python'
>>> word[5]
'n'
>>> word[-2]
'o'

抑是切片(Slicing):

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

m̄-koh,有一點佮 Lists 無仝: 字串是 "袂改得"(immutable),所以下跤的運算是袂用得:
>>> 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'

落尾手,有一咧本底就有的函數會使算字串的長度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

以上一寡例,是uì Python Tutorial 提來个,逐家有興趣會當去參考

沒有留言:

佇 Linux 來看GPX 檔案

最近定定有戶外活動。使用𤆬路機 (GPS) 來記錄行過的路線。普通我記錄路線,攏是用手機仔抑是專門个𤆬路機,罕得用電腦來看。 毋過,"仙人拍鼓有時錯,跤步踏差啥人無"。有一擺我無細膩,袂記得共一擺活動的路線收煞起來,閣直接開始記錄下一擺的活動,按呢共幾落...