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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。