Skip to content

[Python] 字串(string)大小寫轉換的各種方法

使用 Python 來處理字串的大小寫轉換、或是大小寫字串的比對是一件份外輕鬆的事情。一來 Python 本身就屬於簡單又好寫的程式語言,二來這些常用的大小寫轉換方法早就被內建在 Python 的字串(str)處理中了。

今天就分別紀錄以下不同的 Python 字串大小寫處理:

  • 判斷大小寫
  • 轉換大小寫

判斷大小寫

  • islower(): 判斷字串是否全部都是小寫
  • isupper(): 判斷字串是否全部都是大寫
  • istitle(): 判斷字串是否符合標題格式(首字母大寫)
a = "lower"
b = "UPPER"
c = "This Is A Title"

print(a.islower())
print(b.isupper())
print(c.istitle())


Output:

True
True
True



轉換大小寫

  • lower(): 將字串中所有字元轉換成小寫字母
  • upper(): 將字串中所有字元轉換成大寫字母
  • capitalize(): 將第一個字母轉換成大寫字母、其他則為小寫字母
  • title(): 將每個單詞首字母轉換成大寫,其他則為小寫字母
s = "there is a BIG news!"

print("lower():", s.lower())
print("upper():", s.upper())
print("capitalize():", s.capitalize())
print("title():", s.title())


Output:

lower(): there is a big news!
upper(): THERE IS A BIG NEWS!
capitalize(): There is a big news!
title(): There Is A Big News!



References


Read More

Tags:

Leave a Reply