📜  Python String casefold() 方法

📅  最后修改于: 2022-05-13 01:54:43.124000             🧑  作者: Mango

Python String casefold() 方法

Python String casefold()方法用于实现无字符串匹配。它类似于 lower()字符串方法,但 case 删除了字符串中存在的所有大小写区别。即比较时忽略大小写。

示例 1:转换小写字符串

Python3
# Python program to convert string in lower case
string = "GEEKSFORGEEKS"
 
# print lowercase string
print("lowercase string: ",string.casefold())


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 = "".join(reversed(str))
# check if the string is equal to its reverse
if str == rev_str:
      print("palindrome")
else:
      print("not palindrome")


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)


输出:

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 = "".join(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}