Enter ‘*’ between two identical characters in a string using Python

If you are a Computer Science student, I believe you like problems which test your logic building abilities. Well, your wait is over because today we are going to solve the problem of your liking.
In this tutorial, we will learn how to enter ‘*’ or any character for that matter, between two identical characters in a string using Python. I know you are excited, so without further ado let’s get started.

Enter * between two identical characters in a string

First of all, we will need a string.

my_string="Coddee sspeedyy"

We will now create an empty string which will store our required output.

new_string=""
i=0

Here, is an iterator initialized to zero for our while loop.

while(i<len(my_string)-1):

Instead of while loop, we can also use for loop.

for i in range(0,len(my_string)-1):

new_string is our required string so we concatenate each character of my_string to new_string inside our loop.

new_string = new_string + my_string[i]

Its time to compare each character of my_string to the characters stored in the next index. If they are equal, we will enter * between them.

if(my_string[i] == my_string[i+1]):
new_string += '*'

This new new_string is concatenated with the previous new_string. We saw that in our previous statement.

Now we need to increment our iterator.

i+=1

By the end of our while loop, we will have our required string in new_string.
Let’s now print it

print(new_string)

Finally, our code looks like this,

my_string="Coddee sspeedyy"
new_string=""
i=0
while(i<len(my_string)-1):
new_string = new_string + my_string[i]
if(my_string[i] == my_string[i+1]):
new_string += '*'
i+=1
print(new_string)

If you use for loop, the code will be,

my_string="Coddee sspeedyy"
new_string=""
i=0
for i in range(0,len(my_string)-1):
new_string = new_string + my_string[i]
if(my_string[i] == my_string[i+1]):
new_string += '*'
print(new_string)

Output:

Cod*de*e s*spe*edy*

Also, learn:

One response to “Enter ‘*’ between two identical characters in a string using Python”

1. Purnendu says:

Your post is good but the last character is not printed. Please correct this.

On while loop it will be:

my_string=”Coddee sspeedyy”
new_string=””
i=0
while(i<=(len(my_string)-1)):
if(i==len(my_string)-1):
new_string = new_string + my_string[i]
elif(my_string[i] == my_string[i+1]):
new_string = new_string + my_string[i]
new_string += '*'
else:
new_string = new_string + my_string[i]
i+=1
print(new_string)

==========================

For loop will be:

my_string="Coddee sspeedyy"
new_string=""
i=0
for i in range(len(my_string)):
if(i==len(my_string)-1):
new_string = new_string + my_string[i]
elif(my_string[i] == my_string[i+1]):
new_string = new_string + my_string[i]
new_string += '*'
else:
new_string = new_string + my_string[i]
print(new_string)

Then we got our desired output.
The output will be:

Cod*de*e s*spe*edy*y