共計 580 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用字符串的內置方法來改變字符串的大小寫。以下是幾個常用的方法:
- upper():將字符串中的所有字母轉換為大寫。
- lower():將字符串中的所有字母轉換為小寫。
- capitalize():將字符串的首字母轉換為大寫,其他字母轉換為小寫。
- swapcase():將字符串中的大寫字母轉換為小寫,小寫字母轉換為大寫。
- title():將字符串中的每個單詞的首字母轉換為大寫,其他字母轉換為小寫。
下面是示例代碼:
# 將字符串轉換為大寫
str1 = "Hello World"
str1 = str1.upper()
print(str1) # 輸出:HELLO WORLD
# 將字符串轉換為小寫
str2 = "Hello World"
str2 = str2.lower()
print(str2) # 輸出:hello world
# 首字母大寫,其他字母小寫
str3 = "hello world"
str3 = str3.capitalize()
print(str3) # 輸出:Hello world
# 大小寫互換
str4 = "Hello World"
str4 = str4.swapcase()
print(str4) # 輸出:hELLO wORLD
# 每個單詞首字母大寫
str5 = "hello world"
str5 = str5.title()
print(str5) # 輸出:Hello World
丸趣 TV 網 – 提供最優質的資源集合!
正文完