1. 程式人生 > >Python學習筆記(三)——字串操作

Python學習筆記(三)——字串操作

字串字面量

雙引號

>>> spam = "This is Tom' cat"
>>> spam
"This is Tom' cat"

轉義字元

>>> print('\',\",\t,\n,\\')
',",    ,
,\

原始字串

在引號之前加上r,使他成為原始字

>>> print(r'That is Carol\' cat')
That is Carol\' cat

用三重引號的多行字串

>>> print('''Dear Tom:
Thank for your help
Tjanks;
Lili'''
) Dear Tom: Thank for your help Tjanks; Lili

字串下標和切片

>>> spam = 'hello world!'
>>> spam[0]
'h'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'hello'
>>> spam[:5]
'hello'
>>> spam[6:]
'world!'

字串中的innot in 操作符

>>> 'hello'
in 'hello word!' True

有用的字串方法

字串方法upper(),lower(),isupper(),islower()

>>> spam = 'Hello word!'
>>> spam.upper()
'HELLO WORD!'
#將字串中的字母轉換為大寫
>>> spam = spam.lower() 
>>> spam
'hello word!'
#將字串中的字母轉換為小寫
>>> spam.islower()
False
#判斷spam中字元是否都為小寫
>>> 
'hello'.isupper() False #判斷字串中字元是否全為大寫 'H2'.isupper() True #自動忽略非字母的部分

例子:

print('How are you')
feeling = input()
if feeling.lower() == 'great':
    print('I feel great too.')
else:
    print('I hope the rest of your day is good.')


RESTART: 
How are you
greAT
I feel great too.

isX字串方法

  • isalpha() 返回Ture,字串只包含字母,並且非空
>>> 'hello'.isalpha()
True
>>> 'hello '.isalpha()
False
>>> 'hello1223'.isalpha()
False
  • isalnum()返回Ture,字串只包含數字和字母,並且非空
>>> 'hello'.isalnum()
True
>>> 'hello '.isalnum()
False
>>> 'h545'.isalnum()
True
  • isdecimal() 返回True,字串只包含數字,並且非空
>>> '123'.isdecimal()
True
>>> 'hello123'.isdecimal()
False
  • isspace 返回True,字串只包含空格、製表符、換行並且非空
>>> ' '.isspace()
True
  • istitle()返回True,字串僅已大寫字母開頭
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is Title Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case'.istitle()
False

字串方法`startswith()’和’endswith()’

>>> 'hello word!'.startswith('Hello')
False
>>> 'hello word!'.startswith('hello')
True
>>> 'hello word!'.startswith('he')
True
>>> 'hello word!'.startswith('h')
True
>>> 'hello word!'.endswith('!')
True
>>> 'hello word!'.endswith('word!')
True
>>> 'hello word!'.endswith('d')
False

字串方法join()split()

>>> '--'.join(['cats','rats','bats'])
'cats--rats--bats'
#組合字串
>>> 'My nmae is Simon'.split()
['My', 'nmae', 'is', 'Simon']
#拆分字串

rjust()ljust()center() 方法對齊

>>> 'Hello'.rjust(10)
'     Hello'
>>> 'Hello'.rjust(20)
'               Hello'
>>> 'Hello'.ljust(10)
'Hello     '
>>> 'Hello '.center(10)
'  Hello   '
>>> 'Hello'.center(5)
'Hello'
#當字元不夠是才行填充
>>> 'Hello'.center(4)
'Hello'

預設填充為空格

>>> 'Hello'.rjust(20,'*')
'***************Hello'
>>> 'Hello'.ljust(10,'-')
'Hello-----'
>>> 'Hello'.center(10,'+')
'++Hello+++'

strip()rstrip()lstrip() 刪除空白字元

>>> ' hello word '.strip()
'hello word'
>>> ' hello word'.lstrip()
'hello word'
>>> 'hello word '.rstrip()
'hello word'

strip() 括號中的字母順序不影響結果

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.rsplit()
['SpamSpamBaconSpamEggsSpamSpam']
>>> spam.rstrip('Spam')
'SpamSpamBaconSpamEggs'
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.rstrip('mapS')
'SpamSpamBaconSpamEggs'
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.rstrip('mpaS')
'SpamSpamBaconSpamEggs'
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('Spam')
'BaconSpamEggs'

pyperclip模組拷貝貼上字串

pyperclip()模組有copy()paste() 兩個函式,可以向計算機的剪貼簿傳送文字、或者從它接收文字

>>> import pyperclip
>>> pyperclip.copy('Hello')
>>> pyperclip.paste()
'Hello'

小專案——口令保險箱

#! python3
# pw.py - An insecure password locker program.

PASSWORDS = {'email':'[email protected]',
             'blog':'http://blog.csdn.net/mq_go',
             'luggage':'123456' }
import sys,pyperclip
if len(sys.argv)<2:
    print('Usage:python pw.py [account] - copy account password')
    sys.exit()

account = sys.argv[1]  #這裡應該是account name

if account in PASSWORDS:
    pyperclip.copy(PASSWORDS[account])
    print('Password for ' + account + ' is copied to clipboard.')
else:
    print('There is no account named '+ account)

小專案——在Wiki標記中新增無序列表

#! python3
# bulletPointAdder.py

import pyperclip
text = pyperclip.paste()

temp = text.split('\n')
for i in range(len(temp)):
    temp[i] = '* ' + temp[i]

text = '\n'.join(temp)
pyperclip.copy(text)