>>> 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
每乙個字串物件都有幾個可用的內建方法。
>>> s = "shi yan lou
">>>s.title()
'shi yan lou
'
>>> z =s.upper()>>>z
'shi yan lou
'>>>z.lower()
'shi yan lou
'
>>> s = "i am a programmer
">>s.swapcase()
'i am a programmer
'
>>> s = "jdwb 2323bjb
">>>s.isalnum()
false
>>> s = "
jdwb2323bjb
">>>s.isalnum()
true
>>> s = "1234
">>> s.isdigit() #
檢查字串是否所有字元為數字
true
>>> s = "
shiyanlou is coming
">>> s.islower() #
檢查字串是否所有字元為小寫
false
>>> s = "
shiyanlou is coming
">>> s.istitle() #
to 檢查字串是否為標題樣式
true
>>> s = "
china
">>> s.isupper() #
檢查字串是否所有字元為大寫
true
>>> s = "we all love python
">>>s.split()['
we', '
all', '
love
', '
python']
>>> x = "
shiyanlou:is:waiting
">>> x.split(':'
)['shiyanlou
', '
is', '
waiting
']
>>> "-".join("
gnu/linux is great
".split())
'gnu/linux-is-great
'
在上面的例子中,我們基於空格" "
分割字串"gnu/linux is great"
,然後用"-"
連線它們。
最簡單的乙個是strip(chars)
,用來剝離字串首尾中指定的字元,它允許有乙個字串引數,這個引數為剝離哪些字元提供依據。不指定引數則預設剝離掉首尾的空格和換行。
**如下:
>>> s = "a bc\n
">>>s.strip()
'a bc
'>>> s = "
www.foss.in
" >>> s.lstrip("
cwsd.
") #
刪除在字串左邊出現的'c','w','s','d','.'字元
'foss.in
'>>> s.rstrip("
cnwdi.
") #
刪除在字串右邊出現的'c','n','w','d','i','.'字元
'www.foss
'
字串有一些方法能夠幫助你搜尋字串裡的文字或子字串。下面給出示例:
>>> s = "faulty for a reason
">>> s.find("
for")7
>>> s.find("
fora")
-1>>> s.startswith("
fa") #
檢查字串是否以 fa 開頭
true
>>> s.endswith("
reason
") #
檢查字串是否以 reason 結尾
true
find()
能幫助你找到第乙個匹配的子字串,沒有找到則返回 -1。
回文檢查:
#!/usr/bin/env python3
s = input("
please enter a string: ")
z = s[::-1] #
把輸入的字串s 進行倒序處理形成新的字串z
if s ==z:
print("
the string is a palindrome")
else
:
print("
the string is not a palindrome
")
格式化操作符(%)。
print("my name is %s.i am %d years old
" % ('
shixiaolou
',4))
在這個例子中,%s
為第乙個格式符,表示乙個字串;%d
為第二個格式符,表示乙個整數。格式符為真實值預留位置,並控制顯示的格式。常用的有:
%s 字串(用 str() 函式進行字串轉換)
%r 字串(用 repr() 函式進行字串轉換)
%d 十進位制整數
%f 浮點數
%% 字元「%」
Python學習筆記(四)
dict 用 dict 表示 名字 成績 的查詢表如下 d 名字稱為key,對應的成績稱為value,dict就是通過 key 來查詢 value。key不能重複 花括號 表示這是乙個dict,然後按照 key value,寫出來即可。最後乙個 key value 的逗號可以省略。由於dict也是集...
python學習筆記(四)
0.假設你現在拿到了乙個英語句子,需要把這個句子中的每乙個單詞拿出來單獨處理。sentence i am an englist sentence 這時就需要對字串進行分割。sentence.split split 會把字串按照其中的空格進行分割,分割後的每一段都是乙個新的字串,最終返回這些字串組成乙...
python學習筆記 四
python模組,乙個.py檔案 匯入模組的語法 import importable importable 可以是包或包中的模組 import importable1,importablen import importable as preferred name 第三種語法可能導致名稱衝突 一般寫在...