Hi Programmer,
Today we are going to solve a string problem in python. Here you will get a string containing numbers and some special characters. We have to reverse this string without changing the place of the special characters.
*Input: * "123$456%789*0^"
*Output: * "098$765%432*1^"
So let's start our coding
Solution: 1
seq = "123$456%789*0^"
output = "098$765%432*1^"
chars = ['$', '%', '*', '#', '^']
nums = []
for i in range(len(seq)):
if seq[i] not in chars:
nums.append(seq[i])
nums.reverse()
for j in seq:
if j in chars:
idx = seq.index(j)
nums.insert(idx, j)
reverse = "".join(nums)
print(reverse)
Solution: 2
ip_str = "123$456%789*0^"
rev_str = reversed(ip_str)
op_str = ""
for value in ip_str:
if value.isdigit():
for rev_val in rev_str:
if rev_val.isdigit():
op_str += rev_val
break
else:
op_str += value
print(op_str)
Here there were two types we can solve this problem. There can be more type also if you find anything, let's discuss in the room.
Top comments (0)