Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a String From Iterator in Python?

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?

like image 479
SiAce Avatar asked Sep 17 '25 13:09

SiAce


1 Answers

''.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.

like image 85
chepner Avatar answered Sep 19 '25 01:09

chepner