Python 字符串操作基礎

1.Python 字符串

字符串可以看做是由單個文本字符構成的列表,每個字母構成一個列表元素,可以用下標取值,切片,用於for循環,用len()函數

name = 'Zophoie'
name[2]
name[-3]
name[0:3]

'Zo'in name

'ZO'in name
len(name)

'ZOO'not in name
True
for i in name:
    print('*'*(len(name)))
*******
*******
*******
*******
*******
*******
*******

1.1 可變和不可變數據類型

字符串不可變,只能通過 切片 和 連接 構造新的字符串

sentence = 'Zophie loves me'

new = sentence[:7]+'hates'+sentence[-3:]

new
'Zophie hates me'

2.字符串操作

2.1 處理字符串

## 2.1.1 轉義字符
### \t 表示製表符,相當於 tab鍵
print ('I\'m tall but dumb “baby”,that\'s what they call me\nI don\'t really care ,honestly speaking\nThis is a test \t \\')

## 2.1.2 原始字符串
###引號前加 r ,忽略所有轉義字符
print('I\'m lonely')
print(r'I \'m lonely' )

## 2.1.3 三重引號的多行字符串
### “ 三重引號” 之間的所有引號、 製表符或換行, 都被認爲是字符串的一部分。
print('''what if
I'm powerful enough 
to be weak
''')

# 2.1.4 多行字符串可以用來註釋
'''
三個引號就可以
做多行註釋了嗎
似乎不是一個好的方法
'''
I'm tall but dumb “baby”,that's what they call me
I don't really care ,honestly speaking
This is a test   \
I'm lonely
I \'m lonely
what if
I'm powerful enough 
to be weak

'\n三個引號就可以\n做多行註釋了嗎\n似乎不是一個好的方法\n'
#2.1.5 字符串下標與切片
spam = 'Hello,bae'
spam[3]

#2.1.6 字符串 in 和 not in 操作符
'Hello' in spam
True

2.2 有用的字符串方法

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

spam = spam.upper()
spam
spam.islower()
spam.lower().islower()
True

2.2.1 isX 字符串方法

方法 true when
isalpha() 非空 僅字母
isalnum() 非空 僅字母 數字
isdecimal() 非空 僅數字
isspace() 非空 僅空格、換行、製表符
istitle() 僅包含大寫開頭其餘小寫的單詞(標題)

可以用來驗證用戶輸入內容

2.2.2 字符串方法 startswith() endswith()

'Hello world'.startswith('He')
True
'Hello world'.endswith('12')
False

2.2.3 字符串方法 join() split()

','.join(['I','like','you'])
'I,like,you'
' '.join(['I','miss',"you"])
'I miss you'
'My name is Carol'.split()
['My', 'name', 'is', 'Carol']
'Iabcloveabcyouabcdarling'.split('abc')
['I', 'love', 'you', 'darling']
' '.join('Iabcloveabcyouabcdarling'.split('abc'))  #join split 結合
'I love you darling'

2.2.4 rjust() , rjust() , center() 對齊文本

'hello world'.rjust(20)   #右對齊,
'         hello world'
'hello'.ljust(20,'+')    #左對齊
'+++++++++++++++hello'
'bazinga'.center(20,'=')  #居中
'======bazinga======='

2.2.5 strip() , rstrip() , lstrip() 刪除空白字符串

'  Hello,world  '.strip()         #刪除兩邊空白字符
'Hello,world'
'asbdiabafiaobfa'.strip('absf')   #刪除兩邊指定字符,與順序無關
'diabafiao'

2.2.6 用 pyperclip() 模塊拷貝粘貼字符串

pyperclip 模塊有 copy()和 paste()函數, 可以向計算機的剪貼板發送文本, 或從它接收文本。
將程序的輸出發送到剪貼板, 使它很容易粘貼到郵件、文字處理程序或其他軟件中。
pyperclip 模塊不是 Python 自帶的,要安裝它.

import pyperclip
pyperclip.copy('What\'s the world like')
pyperclip.paste()
"What's the world like"
pyperclip.paste()
"'For example, if I copied this sentence to the clipboard and then called\r\npaste(), it would look like this:"

參考文獻
《Python編程快速上手–讓繁瑣工作自動化》

發佈了30 篇原創文章 · 獲贊 63 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章