How to reverse a string in Python

3 Answers

0 votes
# Python's slicing syntax [start:stop:step]. By providing a step of -1, 
# you tell Python to walk through the string

s = "python java"

s = s[::-1]

print(s)


'''
run:

avaj nohtyp

'''

 



answered Sep 14, 2018 by avibootz
edited Mar 18 by avibootz
0 votes
# built-in reversed() function. Returns an iterator, so you need to 
# concatenate the characters back together using .join().

s = "python java"

s = ''.join(reversed(s))

print(s)


'''
run:

avaj nohtyp

'''

 



answered Sep 14, 2018 by avibootz
edited Mar 18 by avibootz
0 votes
# Use: For Loop

# This is slower than slicing because strings in Python are immutable. 
# Every time you do char + reversed string, 
# Python creates new string in memory.

s = "python java"

reversed_string = ""
for char in s:
    reversed_string = char + reversed_string
print(reversed_string) 



'''
run:
 
avaj nohtyp
 
'''

 



answered Mar 18 by avibootz
...