DEV Community

Abdulla Ansari
Abdulla Ansari

Posted on • Edited on

4 2

Reverse String Without Changing Place of Special Characters

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)

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

Buy me a coffee

My other Blog Website over Technology

My YouTube Vlog Channel

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay