4
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'
4

2 回答 2

7

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

str.casefold()文档中:

3.3 版中的新功能。

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

除了自己实现 Unicode 大小写折叠算法之外,没有其他好的选择。请参阅如何在 Python 2 中对字符串进行大小写折叠?

但是,由于您在这里处理的是字节串(而不是 Unicode),因此您可以使用str.lower()并完成它。

于 2015-05-19T14:09:21.233 回答
1

在 python 2.x 中,当你使用casefold().

您可以只使用lower(),这些不相同但可比较。

阅读:str.casefold()

大小写折叠类似于小写,但更具侵略性,因为它旨在删除字符串中的所有大小写区别。例如,德语小写字母“ß”相当于“ss”。由于它已经是小写字母,因此 lower() 不会对 'ß' 做任何事情;casefold() 将其转换为“ss”。

于 2017-08-02T09:09:21.703 回答