Search code examples
pythonfunctionsplitord

Formatting issue involving lists


I've got this function that takes a name as an input, puts it into a list and then runs ord() against it. However, I am having some (what I believe) to be formatting issues. I'm trying to get it to appear like so:

b = (ascii value)
a = (ascii value)
t = (ascii value)
m = (ascii value)
a = (ascii value)
n = (ascii value)

I've got the name appearing correctly, however the ascii value is appearing like this:

b = [98, 97, 116, 109, 97, 110]
a = [98, 97, 116, 109, 97, 110]
t = [98, 97, 116, 109, 97, 110]
m = [98, 97, 116, 109, 97, 110]
a = [98, 97, 116, 109, 97, 110]
n = [98, 97, 116, 109, 97, 110]

Not sure where I'm going wrong, below is the code that I've made for it:

def x():
     name = requestString("name")
     usersName = list(name)
     ascii = [orc(c) for c in usersName]
     for name in name: 
          print name, "=", ascii 

Thanks!

edit: Thanks, it's really appreciated. Get where I went wrong now!


Solution

  • Here's a bit of review of where you went wrong:

    def x():
         name = requestString("name")
         usersName = list(name)
         ascii = [orc(c) for c in usersName] # here's the list
         for name in name: 
              print name, "=", ascii # and you're printing it here everytime
    

    You could fix more pythonically like this:

    def x():
         name = requestString("name")
         # usersName = list(name) # no need for this line, you can iterate over the string
         ascii = [orc(c) for c in name] #so this is just name
         for i, c in enumerate(name):  # use c for your character var name, 
              print c, "=", ascii[i]   # and enumerate provides the index
    

    Since you're not returning anything, creating a list is unnecessary, you might as well provide the ord(c) on the fly:

    def print_ords_of_word(name):
        for c in name:
            print c, '=', ord(c)