1

New to Python and I was wondering if anyone could guide me in the right direction.

For example:

a = "string"

s = list(a)

That turns "string" into ['s', 't', 'r', 'i', 'n', 'g']

But how can I reverse the list and print out "gnirts" without using the built in reverse method from Python.

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
lg713
  • 43
  • 4

2 Answers2

2

To get string characters in reversed order no need to convert the string into list - use reversed slicing:

a = "string"
print(a[::-1])

The output:

gnirts

Some helpful topic about Python's slice notation:

Explain Python's slice notation

Community
  • 1
  • 1
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

Probably the simplest way is just reverse your string using slice notation:

a = 'string'
print(a[::-1])

You can also convert your string to a list, then reverse it and finally join all together by:

a = 'string'
print(''.join(list(a)[::-1])

You can also use a for loop which is a little bit more complicated:

inversed_a = ''

for i in range(len(a) - 1, -1):
    inversed_a += a[i]

then inversed_a will be 'gnirts'

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228