詳述python中的字符串(string)

00 cat's 的打法

print('my cat\'s ball')
my cat's ball

print("my cat's ball")
my cat's ball

01 轉義字符

print('my cat\'s ball') #單引號
my cat's ball

print('my cat\"s ball') #雙引號
my cat"s ball

print('my cat\nball') #換行
my cat
ball

print(r'my cat\nball') # 忽略轉義
my cat\nball

02 三引號與換行

print('''Dear Leslie

My cat
Alice''') #三引號
Dear Leslie

My cat
Alice

print('Dear Leslie\n\nMy cat\nAlice') #換行
Dear Leslie

My cat
Alice

03 注釋

#單行注釋

""" 多

注釋"""

04 upper,lower,isupper,islower

ex='hello World'
ex.upper()
Out[61]: 'HELLO WORLD'

ex.lower()
Out[62]: 'hello world'

'hello world!'.islower()
Out[65]: True

'HELLO!'.isupper()
Out[68]: True

05 isalpha,isdecimal,isalnum,istitle

'hello world'.isalpha()
Out[70]: False

'helloworld'.isalpha() #都是字母,不含標點和空格
Out[71]: True

'12 34'.isdecimal()
Out[75]: False

'h1234'.isdecimal()
Out[76]: False

'1234'.isdecimal() #都是數字,不含標點和空格
Out[77]: True

'h123'.isalnum() #都是字母或數字,不含標點和空格
Out[78]: True

'h 123'.isalnum()
Out[79]: False

'This Is Title Case'.istitle() #每個單詞首個字母是大寫,其它為小寫
Out[81]: True

06 startswith,endswith

ex='hello World'
ex.startswith('hel')
Out[85]: True

  ex='hello World!'
ex.endswith('d!')
Out[89]: True

07 join,split

','.join(['my','name','is','leslie']) #將字符串列表轉化為字符串
Out[2]: 'my,name,is,leslie'

' '.join(['my','name','is','leslie'])
Out[3]: 'my name is leslie'

'ABC'.join(['my','name','is','leslie'])
Out[4]: 'myABCnameABCisABCleslie'

'my name is leslie'.split() #將字符串轉化為字符串列表
Out[8]: ['my', 'name', 'is', 'leslie'] #包含空格

'my,name,is,leslie'.split()
Out[10]: ['my,name,is,leslie']

'myABCnameABCisABCleslie'.split('AB')
Out[11]: ['my', 'Cname', 'Cis', 'Cleslie']

08 rjust,ljust,center

'Hello'.rjust(10,'*')
Out[12]: '*****Hello'

'Hello'.ljust(8,'*')
Out[13]: 'Hello***'

'Hello'.center(12,'*')
Out[14]: '***Hello****'

'Hello'.center(12)
Out[15]: '   Hello    '

09 rstrip,lstrip,strip

'   Hello   '.rstrip() #去除右邊的空格
Out[16]: '   Hello'

'   Hello   '.lstrip() #去除左邊的空格
Out[17]: 'Hello   '

'   Hello   '.strip() #去除兩邊的空格
Out[18]: 'Hello'

'Hello my dear hello'.strip('eH') #去除相應的字母
Out[19]: 'llo my dear hello'

'Hello my dear hello'.lstrip('eH')
Out[20]: 'llo my dear hello'

'Hello Hello my dear hello'.strip('Hello') #空格
Out[21]: ' Hello my dear h'

10 pyperclip擴展庫

pip install pyperclip #安裝pyperclip擴展庫
import pyperclip #導入擴展庫
pyperclip.copy('hello sb') #復制hello sb 到電腦的剪切板
pyperclip.paste() #黏貼

登錄后免費查看全文
立即登錄
App下載
技術鄰APP
工程師必備
  • 項目客服
  • 培訓客服
  • 平臺客服

TOP

3
1