开发者

python - ordinal value - list indices must be integers not str

what i want to do is take a string and for each character make 开发者_如何学Pythonthe ordinal value 1 more from the value it has.

myinput=input("Message : ")

mylist =list(myinput) #convert to list in order to take each character

for character in mylist:
    mylist[character]+=ord(mylist[character])+1
print(character)

The problem is with the "ord(mylist[character])+1"

Thank you!


Probably you are looking for the next:

>>> m = raw_input('Message:')
Message:asdf
>>> ''.join(chr(ord(c) + 1) for c in m)
'bteg'

Notes:

  • use raw_input when you need to get string input from a user;
  • ord convert character to integer, chr - vise versa;
  • ... for c in m syntax is a generator expression. It is also used for list comprehension.


Three problems here. First, you're mixing up list indices and list elements. Second, you didn't convert back to a character (I'm assuming you want characters, not numbers). Third, you're adding to the existing value.

One way:

for i range(len(mylist)):
    mylist[i] = chr(ord(mylist[i])+1)

Another way:

for i, character in enumerate(mylist):
    mylist[i] = chr(ord(character)+1)


Instead of

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

(where character is a list index and therefore invalid), you probably want:

mylist = [ord(character) + 1 for character in mylist]

Or a Counter.


You can do like this

def ordsum(astring, tablesize): sum = 0 for num in range(len(astring)): sum = sum + ord(astring[num])

return sum


myinput = input() # use raw_input() in Python 2
myinput = map(lambda ch: chr(ord(ch) + 1), myinput)
# or list comp.
myinput = [chr(ord(ch) + 1) for ch in myinput]


You can iterate directly over a string, you do not have to make it a list first. If your end goal is to have a new string, you can do this:

myinput=input("Message : ")

result = []
for character in myinput:
    result.append( chr( ord( character ) + 1 )
mynewstring = ' '.join(result)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜