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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

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

Sign up