How to change a string using a list

Here I am trying to change a string using the following logic,

st = "This is Ok"
rst = list(st)
rst.reverse()
''.join(s for s in rst)

It works fine, but when I try to follow the logic below, I get an error message,

st = "This is Ok"
''.join(s for s in list(st).reverse())

Here is the mistake

----> 1 ''.join(s for s in list(st).reverse())

TypeError: 'NoneType' object is not iterable

Please explain the above process.

+4
source share
4 answers

list.reverseis an inplace operation, so it will change the list and return None. You should use a function reversedlike

"".join(reversed(rst))

I personally would recommend using notation slicing like this

rst[::-1]

For example,

rst = "cabbage"
print "".join(reversed(rst))   # egabbac
print rst[::-1]                # egabbac
+5
source

Have you tried the following?

"".join(s for s in reversed(st))

reversedreturns the return iterator. Documentation here

+3
source

, lst.reverse() None ( None). , , () reversed(lst), lst, .

Note that if you want to change the line, you can do it directly (without lists):

>>> st = "This is Ok"
>>> st[::-1]
"kO si sihT"
+2
source

Try it?

[x for x in a[::-1]]

[x for x in reversed(a)]

Both work fine, but are more efficient with [:: - 1]

min(timeit.repeat(lambda: [x for x in a[::-1]]))

Out [144]: 0.7925415520003298

min(timeit.repeat(lambda: [x for x in reversed(a)]))

Out [145]: 0.854458618996432

0
source

Source: https://habr.com/ru/post/1527837/


All Articles