'Reverse string without affecting special character
I'm trying to reverse a string without affecting special characters, but it is not working. Here is my code:
def reverse_each_word(str_smpl):
str_smpl = "String; 2be reversed..." #Input that want to reversed
lst = []
for word in str_smpl.split(' '):
letters = [c for c in word if c.isalpha()]
for c in word:
if c.isalpha():`enter code here`
lst.append(letters.pop())
continue
else:
lst.append(c)
lst.append(' ')
print("".join(lst))
return str_smpl
def main(): #This is called for assertion of output
str_smpl = "String; 2be reversed..." #Samplr input
assert reverse_each_word(str_smpl) == "gnirtS; eb2 desrever..." #output should be like this
return 0
Solution 1:[1]
Try the following code:
from string import punctuation
sp = set(punctuation)
str_smpl = "String; 2be reversed..." #Input that want to reversed
lst = []
for word in str_smpl.split(' '):
letters = [c for c in word if c not in sp]
for c in word:
if c not in sp:
lst.append(letters.pop())
continue
else:
lst.append(c)
lst.append(' ')
print("".join(lst))
Hope this will work...
Solution 2:[2]
Or try this with itertools.groupby
,
import itertools
def reverse_special_substrings(s):
ret = ''
for isalnum, letters in itertools.groupby(s, str.isalnum):
letters = list(letters)
if isalnum:
letters = letters[::-1]
ret += ''.join(letters)
return ret
Solution 3:[3]
Do you mean like this?:
def reverse_string(st):
rev_word=''
reverse_str=''
for l in st:
if l.isalpha():
rev_word=l+rev_word
else:
reverse_str+=rev_word
rev_word=''
reverse_str+=l
return reverse_str
def main():
string=' Hello, are you fine....'
print(reverse_string(string))
if __name__=='__main__':
main()
Solution 4:[4]
def reverse_string_without_affecting_number(text):
temp = []
text = list(text)
for i in text:
if not i.isnumeric():
temp.append(i)
reverse_temp = temp [::-1]
count = 0
for i in range(0,len(text)):
if not text[i].isnumeric():
text[i] = reverse_temp[count]
count +=1
else:
continue
return "".join(text)
print (reverse_string_without_affecting_number('abc1235de9f15ui'))
Solution 5:[5]
def reversestring(t): c=[] t=list(t) for i in t: if i.isalpha(): c.append(i) reverse_string = c[::-1] count = 0 for i in range(len(t)): if not t[i].isalpha(): reverse_string.insert(i,t[i]) return reverse_string print (reversestring("a@bc%d"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kriti Pawar |
Solution 2 | Aaron |
Solution 3 | Mishal |
Solution 4 | Suraj Rao |
Solution 5 | Goutham Sainath DARA |