4

How to create a string from an iterator over string in Python?

I am currently just trying to create a reversed copy of a string, I know I could just use slice:

s = 'abcde'
reversed_s = s[::-1]

I could also create a list from the iterator and join the list:

s = 'abcde'
reversed_s_it = reversed(s)
reversed_list = list(reversed_s_it)
reversed_s = ''.join(reversed_list)

But when I try to create a string from the iterator directly, it just gives a string representation of the iterator, if I do this:

s = 'abcde'
reversed_s_it = reversed(s)
reversed_s = str(reversed_s_it)

reversed_s will give a string representation of the iterator instead of iterating the iterator to create a string.

print(reversed_s)

Output

<reversed object at 0x10c3dedf0>

Furthermore

print(reversed_s == 'edcba')

Output

False

Therefore, I just want to know if there is a Pythonic way to create a string from an iterator?

11
  • What's wrong with ''.join(reversed(s))? Commented Dec 25, 2020 at 22:30
  • @chepner, I just don't feel good about using an extra space for creating an extra list to construct a string, I'm not sure if there is a better way Commented Dec 25, 2020 at 22:33
  • Iterators can be materialized as lists or tuples by using the list() or tuple() constructor functions. So it is hard to imagine there’s another way to skip this step. Commented Dec 25, 2020 at 22:33
  • String is an iterable object in python. and type(reversed_s) shows it as a str object what do you mean when you say "reversed_s is still an iterator" Commented Dec 25, 2020 at 22:36
  • 1
    @SiAce because that's the string representation of that iterator, which is what you asked for when you did str(reversed_s_it), the same as any object, which just happens to be the default __str__ implementation inherited from object, so, for example, class Foo: pass then print(Foo()) will give you something similar. Commented Dec 25, 2020 at 22:47

1 Answer 1

4

''.join itself only needs an iterable; you don't have to create a list first.

>>> ''.join(reversed(s))
'edcba'

However, there's nothing wrong with s[::-1]; in fact, it's quite a bit faster than using ''.join to concatenated the elements from the reversed object.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, thanks, didn't know about that. By the way, what's the time complexity of join()?
NOTE implementation detail, .join materializes a list underneath the hood anyway.

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.