w3resource

Python: Create a new string with no duplicate consecutive letters from a given string

Python Basic - 1: Exercise-102 with Solution

Write a Python program to create a string with no duplicate consecutive letters from a given string.

Sample Solution:

Python Code:

def no_consecutive_letters (txt):
    return txt[0] + ''.join(txt[i] for i in range(1,len(txt)) if txt[i] != txt[i-1])

print(no_consecutive_letters("PPYYYTTHON"))
print(no_consecutive_letters("PPyyythonnn"))
print(no_consecutive_letters("Java"))
print(no_consecutive_letters("PPPHHHPPP")) 

Sample Output:

PYTHON
Python
Java
PHP

Pictorial Presentation:

Python: Create a new string with no duplicate consecutive letters from a given string.
Python: Create a new string with no duplicate consecutive letters from a given string.

Flowchart:

Flowchart: Python - Create a new string with no duplicate consecutive letters from a given string.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the name of the oldest student from a given dictionary containing the names and ages of a group of students.
Next: Write a Python program to check whether two given lines are parallel or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.