Reversing "group" of strings in Python -
how reverse "groups" (not list) of strings? example convert "123456789" "321654987" given "group" size equals 3.
followings code turns out print empty strings:
string = "12345678901234567890" new_string = "" in range(0, len(string), 5): new_string = new_string + string[i:i+5:-1] print (new_string)
thanks input , advice.
when using negative step, swap start , end values too:
new_string += string[i + 4:i - 1 if else none:-1]
note end value excluded, , none
should used include first character (-1
slice end again , string[4:-1:-1]
empty).
demo:
>>> string = "12345678901234567890" >>> new_string = "" >>> in range(0, len(string), 5): ... new_string = new_string + string[i + 4:i - 1 if else none:-1] ... >>> new_string '54321098765432109876'
however, may easier first slice, reverse, , save headaches of such slicings:
new_string += string[i:i + 4][::-1]
Comments
Post a Comment