While using casefold(), I am getting an error as " AttributeError: 'str' object has no attribute 'casefold' "

While using casefold(), I am getting an error as " AttributeError: 'str' object has no attribute 'casefold' "

vowels = 'aeiou'

# take input from the user
ip_str = raw_input("Enter a string: ")

# make it suitable for caseless comparisions
ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)

# count the vowels
for char in ip_str:
    if char in count:
        count[char] += 1

print(count)

错误:

    Line - ip_str = ip_str.casefold()
AttributeError: 'str' object has no attribute 'casefold'

Python 2.6 不支持 str.casefold() 方法。

来自str.casefold() documentation

New in version 3.3.

您需要切换到 Python 3.3 或更高版本才能使用它。

除了自己实现 Unicode 大小写折叠算法外,没有其他好的选择。参见 How do I case fold a string in Python 2?

但是,由于您在此处处理 bytestring(而不是 Unicode),您可以只使用 str.lower() 并完成它。

在python 2.x中使用casefold()时会报错。

你可以直接用lower(),这两个不一样但是可以比较

阅读:str.casefold()

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".