String Method1

字串型別有的方法

不同的型別都有其所屬的一些方法,這個在物件導向(OOP)概念學完後,就會有一個完整的理解了,我們這邊先來使用看看。

大小寫

我們時常會將字串進行大小寫轉換來進行無大小寫差別的比對,或是直接判斷字串是否為大小寫。

我們來看看以下的範例:

hi = 'How are you?'

# 轉換成小寫
print(hi.lower())
# 轉換成大寫
print(hi.upper())

# 判斷是否為小寫
print(hi.islower())
# 判斷是否為大寫
print(hi.isupper())

判斷字串是否為特定類型字串

string = 'abcde'
# 只有字母且不為空,則為真
print(string.isalpha())

string = '123abc'
# 字串只有數字或字母且不為空,則為真
print(string.isalnum())

string = '0012345'
# 字串只有數字,且不為空,則為真
print(string.isdigit())

string = '\n'
# 字串只含有空格,定位空格,或是換行字元,且不為空,則為真
print(string.isspace())

判斷字串是否以特定形式結尾或開頭

print('This is Jason\'s notebook.'.startswith('This'))

print('This is Jason\'s notebook.'.endswith('book.'))

Last updated

Was this helpful?