【问题标题】:While using casefold(), I am getting an error as " AttributeError: 'str' object has no attribute 'casefold' "在使用 casefold() 时,我收到一个错误,因为“AttributeError: 'str' object has no attribute 'casefold'”
【发布时间】:2015-05-19 14:08:09
【问题描述】:
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 python-2.6 case-folding


    【解决方案1】:

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

    来自str.casefold() documentation

    3.3 版中的新功能。

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

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

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

    【讨论】:

    • 你能解释一下这个语句 count = {}.fromkeys(vowels,0)
    • 在上面的评论中 { }.fromkeys() 是什么意思
    • @NikhilKadam:这是使用dict.fromkeys() class method 的一种相当谨慎的方式,它使用vowels 中的元素作为键创建一个新字典,每个值都设置为0
    【解决方案2】:

    在 python 2.x 中使用casefold() 时会出现错误。

    你可以直接使用lower(),它们不一样,但可以比较。

    阅读:str.casefold()

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

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多