6

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))
4
  • 1
    map returns a generator in Python3, try: return "".join(list(map(lambda i: alph[(alph.find(i)+13) % len(alph)], string))) Commented May 23, 2018 at 15:27
  • You can turn a string into a list with something like a_list = list(a_string). Commented May 23, 2018 at 15:40
  • 1
    @MauriceMeyer map returns a map object, not a generator Commented May 23, 2018 at 16:02
  • Yes. map always returns a map object. No matter the iterable you are napping over. It is meant to work with any iterable. Commented May 23, 2018 at 16:06

2 Answers 2

10

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)
Sign up to request clarification or add additional context in comments.

Comments

8

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

1 Comment

map does not return a generator, it returns a map-object, which is an iterator but not a generator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.