Reverse a string in Python
Using slicing:
>>> 'hello world'[::-1]
'dlrow olleh'
Slice notation takes the form [start:stop:step]
. In this case, we omit the start
and stop
positions since we want the whole string. We also use step = -1
, which means, "repeatedly step from right to left by 1 character".
How to reverse the words of a string considering the punctuation?
Try this (explanation in comments of code):
s = "Do or do not, there is no try."
o = []
for w in s.split(" "):
puncts = [".", ",", "!"] # change according to needs
for c in puncts:
# if a punctuation mark is in the word, take the punctuation and add it to the rest of the word, in the beginning
if c in w:
w = c + w[:-1] # w[:-1] gets everthing before the last char
o.append(w)
o = reversed(o) # reversing list to reverse sentence
print(" ".join(o)) # printing it as sentence
#output: .try no is there ,not do or Do
how to reverse a string in python without changing the position of words?
Just create a new empty str variable and concatenate it.
str5 = 'peter piper picked a peck of pickled peppers.'
b = str5.split()
rev_str5 = ""
for i in b:
rev_str5 = rev_str5 + ' ' + i[::-1]
print(rev_str5.lstrip()) # Removes the one space in the starting.
Here's a shorter method too. Thanks for the comment:
str5 = 'peter piper picked a peck of pickled peppers.'
print(' '.join(w[::-1] for w in str5.split()))
Output:
retep repip dekcip a kcep fo delkcip .sreppep
How do I reverse words in a string with Python
def reverseStr(s):
return ' '.join([x[::-1] for x in s.split(' ')])
Reverse string without non letters symbol
You were really close! Your code is not working because you are applying the reversion to the whole string instead of doing it one word at a time. But just adding an extra step that splits the input string at white spaces (I assume white spaces is what defines words in your input) you'll get your desired result:
def reverse_string(st):
return ' '.join(reverse_word(word) for word in st.split())
def reverse_word(st):
stack = []
for el in st:
if el.isalpha():
stack.append(el)
result = ''
for el in st:
if el.isalpha():
result += stack.pop()
else:
result += el
return result
instr = 'b3ghcd hg#tyj%h'
print(reverse_string(instr)) # prints 'd3chgb hj#ytg%h'
NOTE:
You can pythonify your code a bit using some built in functions of list comprehension. In this case you'd replace the building of your stack
.
stack = []
for el in st:
if el.isalpha():
stack.append(el)
for one of the following:
stack = [el for el in st if el.isalpha()]
orstack = list(filter(str.isalpha, st))
Related Topics
What Is the Purpose and Use of **Kwargs
Convert Pandas Column to Datetime
Switch to an Iframe Through Selenium and Python
Use 'Import Module' or 'From Module Import'
How to Read a Large CSV File With Pandas
Generator Expressions Vs. List Comprehensions
Difference Between '/' and '//' When Used For Division
Does Pandas Iterrows Have Performance Issues
How to Parse Data in Json Format
Faster Version of 'Pygame.Event.Get()'. Why Are Events Being Missed and Why Are the Events Delayed
How to Sort a List/Tuple of Lists/Tuples by the Element At a Given Index
Selenium Using Python - Geckodriver Executable Needs to Be in Path
Selenium in Python: Nosuchelementexception: Message: No Such Element: Unable to Locate Element
How to Run Your Own Code Alongside Tkinter'S Event Loop