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 new 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.



Python: Tips of the Day

What is the difference between Python's list methods append and extend?

append: Appends object at the end.

x = [1, 2, 3]
x.append([4, 5])
print (x)

Output:

[1, 2, 3, [4, 5]]

extend: Extends list by appending elements from the iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

Output:

[1, 2, 3, 4, 5]

Ref: https://bit.ly/2AZ6ZFq