Python String casefold() 方法用於實現無大小寫的字符串匹配。它類似於 lower() 字符串方法,但 case 刪除了字符串中存在的所有大小寫區別。即在比較時忽略案例。
用法:
string.casefold()
參數:
casefold() 方法不帶任何參數。
返回值:
它返回轉換為小寫的字符串的大小寫折疊字符串。
示例 1:將字符串轉換為小寫
Python3
# Python program to convert string in lower case
string = "GEEKSFORGEEKS"
# print lowercase string
print("lowercase string:",string.casefold())
輸出:
lowercase string:geeksforgeeks
示例 2:檢查字符串是否為回文
Python3
# Program to check if a string
# is palindrome or not
# change this value for a different output
str = 'geeksforgeeks'
# make it suitable for caseless comparison
str = str.casefold()
# reverse the string
rev_str = reversed(str)
# check if the string is equal to its reverse
if str == rev_str:
print("palindrome")
else:
print("not palindrome")
輸出:
not palindrome
示例 3:計算字符串中的元音
Python3
# Program to count
# the number of each
# vowel in a string
# string of vowels
v = 'aeiou'
# change this value for a different result
str = 'Hello, have you try geeksforgeeks?'
# input from the user
# str = input("Enter a string:")
# caseless comparisions
str = str.casefold()
# make a dictionary with
# each vowel a key and value 0
c = {}.fromkeys(v,0)
# count the vowels
for char in str:
if char in c:
c[char] += 1
print(c)
輸出:
{'a':1, 'e':6, 'i':0, 'o':3, 'u':1}
相關用法
- Python String center()用法及代碼示例
- Python String count()用法及代碼示例
- Python String endswith()用法及代碼示例
- Python String find()用法及代碼示例
注:本文由純淨天空篩選整理自GeeksforGeeks大神的英文原創作品 Python String casefold() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。