简体   繁体   中英

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)

Error:

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

Python 2.6 doesn't support the str.casefold() method.

From the str.casefold() documentation :

New in version 3.3.

You'll need to switch to Python 3.3 or up to be able to use it.

There are no good alternatives, short of implementing the Unicode casefolding algorithm yourself. See How do I case fold a string in Python 2?

However, since you are handling a bytestring here (and not Unicode), you could just use str.lower() and be done with it.

In python 2.x you will get an error when you use casefold() .

You may just use lower() , these are not the same but comparable.

Read: 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM