Use map() function with string

17,071

Solution 1

Using list/generator comprehensions is preferable (more Pythonic) to map():

def rot_13(string):
    alph = 'abcdefghijklmnopqrstuwxyz'
    return ''.join(alph[(alph.find(i)+13) % len(alph)] for i in string)

Solution 2

python3 map returns a generator, so you have to consume it, using str.join is the easiest way:

"".join(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string))

It is similar to this code:

my_string = ""
for l in map(lambda i: alph[(alph.find(i)+13) % len(alph)], string):
    my_string += l
Share:
17,071
bertonc96
Author by

bertonc96

Updated on June 06, 2022

Comments

  • bertonc96
    bertonc96 almost 2 years

    Is there a way to use map() function with a string instead of a list? Or the map() function is meant only to work with lists?

    For instance, ignoring the content of the lambda function, this code returns a map object and not a string:

    def rot_13(string):
        alph = 'abcdefghijklmnopqrstuwxyz'
        return str(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string))
    
    • Maurice Meyer
      Maurice Meyer almost 6 years
      map returns a generator in Python3, try: return "".join(list(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string)))
    • martineau
      martineau almost 6 years
      You can turn a string into a list with something like a_list = list(a_string).
    • juanpa.arrivillaga
      juanpa.arrivillaga almost 6 years
      @MauriceMeyer map returns a map object, not a generator
    • juanpa.arrivillaga
      juanpa.arrivillaga almost 6 years
      Yes. map always returns a map object. No matter the iterable you are napping over. It is meant to work with any iterable.
  • bertonc96
    bertonc96 almost 6 years
    Thanks, I think it's the best way
  • juanpa.arrivillaga
    juanpa.arrivillaga almost 6 years
    map does not return a generator, it returns a map-object, which is an iterator but not a generator.