0%

[學習] Pyton - String

一些關於 String 單字或字首大寫處理的用法

字首大寫

  • capitalize(): 只會將字串的字首轉成大寫,其餘若有大寫的字會轉成小寫
  • title(): 將字串中所有“單字”的字首轉成大寫

input:

1
2
3
text = "greetings, fiends"
print(text.capitalize())
print(text.title())

output:

1
2
'Greetings, friends'
'Greetings, Fiends'

但 capitalize() 可能會遇到一個問題,若是原本句子中有人名或地名,本身字首就是大寫的單子,在使用 capitalize() 後會變成小寫,因此有另一種方法,如下:

input:

1
2
3
text = "welcome to New York"

print(text[0].upper() + text[1:])

output:

1
"Welcome to New York"
  • lower(): 將字串全部轉成小寫
  • upper(): 將字串全部轉成大寫
  • islowewr(): 檢查字串是否全小寫
  • isupper(): 檢查字串是否全大寫

input:

1
2
3
4
5
6
text = "Hi, my Name is Zana"

print(text.lower())
print(text.upper())
print(text.islowewr())
print(text.isupper())

output:

1
2
3
4
"hi, my name is zana"
"HI, MY NAME IS ZANA"
False
False