简体   繁体   中英

Python ord() and chr()

I have:

txt = input('What is your sentence? ')  
list = [0]*128
for x in txt:
    list[ord(x)] += 1
for x in list:
        if x >= 1:
            print(chr(list.index(x)) * x)

As per my understanding this should just output every letter in a sentence like:

))
111
3333
etc.

For the string "aB)a2a2a2)" the output is correct:

))
222
B
aaaa

For the string "aB)a2a2a2" the output is wrong:

)
222
)
aaaa

I feel like all my bases are covered but I'm not sure what's wrong with this code.

When you do list.index(x) , you're searching the list for the first index that value appears. That's not actually what you want though, you want the specific index of the value you just read, even if the same value occurs somewhere else earlier in the list too.

The best way to get indexes along side values from a sequence is with enuemerate :

for i, x in enumerate(list):
    if x >= 1:
        print(chr(i) * x)

That should get you the output you want, but there are several other things that would make your code easier to read and understand. First of all, using list as a variable name is a very bad idea, as that will shadow the builtin list type's name in your namespace. That makes it very confusing for anyone reading your code, and you even confuse yourself if you want to use the normal list for some purpose and don't remember you've already used it for a variable of your own.

The other issue is also about variable names, but it's a bit more subtle. Your two loops both use a loop variable named x , but the meaning of the value is different each time. The first loop is over the characters in the input string, while the latter loop is over the counts of each character. Using meaningful variables would make things a lot clearer.

Here's a combination of all my suggested fixes together:

text = input('What is your sentence? ')  
counts = [0]*128

for character in text:
    counts[ord(character)] += 1

for index, count in enumerate(counts):
        if count >= 1:
            print(chr(index) * count)

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