Page 1 of 1

How to reverse a string in Python?

Posted: Thu Feb 16, 2023 11:54 am
by KalamyQ

I'm writing a Python translator. According to what I discovered after reading this post, this translator will transform a standard text into one with some unique features.

We append "S" at the beginning of each word.
We append "Di" at the end of each word.
Each word example is reversed: Hello Everyone --> SHello SEveryone --> SHelloDi SEveryoneDi --> SHelloDi SEveryoneDi —> iDenoyrevES iDolleHS

The first two sections were simple for me; however, the third portion is a little tough for my code.

Code: Select all

n = input("Enter Text : ")
y = n.split()
z = 0

for i in y:
    x = str("S" + i)
    y[z] = x
    z = z + 1

z = 0

for i in y:
    x = str(i + "Di")
    y[z] = x
    z = z + 1

print(y)

z = 1

for i in y:
    globals()["x%s" % z] = []
    for j in i:
        pass

I'd want to implement something like this in the pass section xi. append(j) and then we reverse it.

How do I go about doing this?
Thanks you


Re: Reverse a String in python

Posted: Sat Feb 18, 2023 1:06 pm
by Burunduk

In that scaler tutorial, the slicing method is the simplest. As you can see from the example below, the order of the angle brackets is reversed. The words should be reversed too but for some mysterious reason they are not:

Code: Select all

# using slicing and regex

import re

text='step on no pets!'
before='<'
after='>'

txet=re.sub(r'\w+', before + r'\g<0>' + after, text)[::-1]

print(txet)

# using a stack and string methods

words=text.split()

text=' '.join([before + i + after for i in words])

stack=[]
for c in text:
    stack.append(c)

txet=''
while len(stack):
    txet=txet + stack.pop()

print(txet)

# note the difference in word splitting: '\w' doesn't match '!'

globals()["x%s" % z] = []

It's not a good idea to make indexes a part of a variable name. If you really need to, you can make a list of lists (howto) and append to the inner ones by x[i].append(elem)