Python 中不區分大小寫的字串比較

  1. 使用 lower() 方法進行不區分大小寫的字串比較
  2. 使用 upper() 方法進行不區分大小寫的字串比較
  3. 使用 casefold() 方法進行不區分大小寫的字串比較
Python 中不區分大小寫的字串比較

本教程將討論在 Python 中對兩個或多個字串變數進行不區分大小寫比較的一些方法。

使用 lower() 方法進行不區分大小寫的字串比較

Python 字串有一個內建的 lower() 方法,可以將字串中的所有字元轉換為小寫字母。它返回一個將所有字元轉換為小寫字母的字串。我們可以使用 lower() 方法將兩個字串轉換為小寫,然後對它們進行不區分大小寫的比較。

normal_str1 = "Hello World!"
lower_str1 = normal_str1.lower()
print(lower_str1)

輸出:

hello world!

現在對第二個字串變數 normal_str2 做同樣的操作。

normal_str2 = "HELLO WORLD!"
lower_str2 = normal_str2.lower()
print(lower_str2)

輸出:

hello world!

正如我們所看到的,兩個字串都被轉換為所有小寫字元。下一步是比較兩個字串變數並顯示輸出。

normal_str1 = "Hello World!"
lower_str1 = normal_str1.lower()
normal_str2 = "HELLO WORLD!"
lower_str2 = normal_str2.lower()

if lower_str1 == lower_str2:
    print("Both variables are equal")
else:
    print("Both variables are not equal")

輸出:

Both variables are equal

使用 upper() 方法進行不區分大小寫的字串比較

上節課介紹瞭如何使用 lower() 方法進行不區分大小寫的字串比較。使用 upper() 方法的邏輯是一樣的。我們要在這兩種方法中把現有的字串變數改成大寫或小寫字元。upper() 方法是字串類的內建方法,可以將一個字串變數的所有字元轉換為大寫字母。

normal_str1 = "Hello World!"
upper_str1 = normal_str1.upper()

normal_str2 = "hello world!"
upper_str2 = normal_str2.upper()

if upper_str1 == upper_str2:
    print("Both variables are equal")
else:
    print("Both variables are not equal")

輸出:

Both variables are equal

使用 casefold() 方法進行不區分大小寫的字串比較

casefold() 方法是一種更激進的方法,用於將字串變數轉換為小寫字元。例如:

有一個德文字母'ß'已經是小寫字母了,所以 lower() 方法對'ß'沒有任何作用。因此,lower() 方法對'ß'沒有任何作用。但是 casefold() 可以將'ß'轉換為"ss"

normal_str = "ß"
casefold_str = normal_str.casefold()
lower_str = normal_str.lower()
print("Case folded form of ß is : " + casefold_str)
print("Lower cased form of ß is : " + lower_str)

輸出:

Case folded form of ß is : ss
Lower cased form of ß is : ß

casefold() 方法返回一個字串變數,在這個變數中,所有的字元都被積極地轉換為小寫。然後,這個新的字串變數可以進行比較,進行不區分大小寫的比較。

normal_str1 = "Hello World ß!"
casefold_str1 = normal_str1.casefold()

normal_str2 = "Hello World ss!"
casefold_str2 = normal_str2.casefold()

if casefold_str1 == casefold_str2:
    print("Both variables are equal")
else:
    print("Both variables are not equal")

輸出:

Both variables are equal
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Python String