How to reverse a string in Python?

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

How to reverse a string in Python?

Post 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

Burunduk
Posts: 245
Joined: Thu Jun 16, 2022 6:16 pm
Has thanked: 6 times
Been thanked: 123 times

Re: Reverse a String in python

Post 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)

Post Reply

Return to “Programming”