Remove unwanted characters

Python Practice › String Programs › Program 21

Remove unwanted characters

EasyString Programs · 21 of 106

Write a Python program to remove every character that is not a letter or digit.

Input
"Prog^ra*m#ming", "Py(th)#@&on Pro$*#gram"
Output
Programming
PythonProgram

Approach

  1. Keep only alphanumeric characters.

Solution

Python
for text in ["Prog^ra*m#ming", "Py(th)#@&on Pro$*#gram"]:    print("".join(ch for ch in text if ch.isalnum()))
Output
Programming
PythonProgram

Line by line

Line 2

Spaces are not alphanumeric either, so “Py… Pro…” becomes one word, matching the expected output.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Remove duplicate words

Python Practice › String Programs › Program 20

Remove duplicate words

EasyString Programs · 20 of 106

Write a Python program to remove duplicate words (ignoring case) and keep the first occurrence.

Input
"John jany sabi row john sabi"
Output
John jany sabi row

Approach

  1. Track lower-cased words already seen.

Solution

Python
text = "John jany sabi row john sabi"seen = set()result = []for w in text.split():    if w.lower() not in seen:        seen.add(w.lower())        result.append(w)print(" ".join(result))
Output
John jany sabi row

Line by line

Line 5

Comparing lower-cased words treats “John” and “john” as the same.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Build a sentence from a list of words

Python Practice › String Programs › Program 19

Build a sentence from a list of words

EasyString Programs · 19 of 106

Write a Python program to create a string from a list of words.

Input
["There", "are", "Many", "Programming", "Language"]
Output
There are Many Programming Language

Approach

  1. " ".join(words).

Solution

Python
words = ["There", "are", "Many", "Programming", "Language"]print(" ".join(words))
Output
There are Many Programming Language

Line by line

Line 2

join puts the separator (a space) between the words.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Palindrome words in a string

Python Practice › String Programs › Program 18

Palindrome words in a string

EasyString Programs · 18 of 106

Write a Python program to get all palindrome words from a string.

Input
"Python efe language aakaa hellolleh"
Output
['efe', 'aakaa', 'hellolleh']

Approach

  1. Keep words equal to their reverse.

Solution

Python
text = "Python efe language aakaa hellolleh"print([w for w in text.split() if w.lower() == w.lower()[::-1]])
Output
['efe', 'aakaa', 'hellolleh']

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Replace Java with Python, any case

Python Practice › String Programs › Program 17

Replace Java with Python, any case

EasyString Programs · 17 of 106

Write a Python program to replace the word “Java” (in any letter case) with “Python”.

Input
"JAVA is the Best Programming Language in the Market"
Output
Python is the Best Programming Language in the Market

Approach

  1. str.replace is case-sensitive, so use re.sub with re.IGNORECASE.

Solution

Python
import re text = "JAVA is the Best Programming Language in the Market"print(re.sub(r"\bjava\b", "Python", text, flags=re.IGNORECASE))
Output
Python is the Best Programming Language in the Market

Line by line

Line 4

\b matches whole words only, and the flag ignores case.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Extract all numbers from a string

Python Practice › String Programs › Program 16

Extract all numbers from a string

EasyString Programs · 16 of 106

Write a Python program to get all the numbers from a multi-line string.

Input
a paragraph containing 1112, 1773, 444, 5324 and 555
Output
[1112, 1773, 444, 5324, 555]

Approach

  1. Use re.findall(r"\d+", text) and convert each match to int.

Solution

Python
import re text = """Sinak's 1112 aim is to 1773 create a new generation of people whounderstand 444 that an organization's 5324 success or failure isbased on 555 leadership excellence and not managerial acumen"""numbers = [int(n) for n in re.findall(r"\d+", text)]print(numbers)
Output
[1112, 1773, 444, 5324, 555]

Line by line

Line 6

\d+ matches each run of digits; the list comprehension converts them to integers.

Note

The original sample output listed 5324 twice and missed 444; the real numbers in the text are shown here.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Reverse the order of words

Python Practice › String Programs › Program 15

Reverse the order of words

EasyString Programs · 15 of 106

Write a Python program to rearrange a sentence so its words appear in reverse order.

Input
"Cricket Plays Virat"
Output
Virat Plays Cricket

Approach

  1. Split, reverse the list, join.

Solution

Python
text = "Cricket Plays Virat"print(" ".join(text.split()[::-1]))
Output
Virat Plays Cricket

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Vowel count of each word

Python Practice › String Programs › Program 13

Vowel count of each word

EasyString Programs · 13 of 106

Write a Python program to count the vowels in each word and show the result as a dictionary.

Input
"We are Learning Python Codding"
Output
{'We': 1, 'are': 2, 'Learning': 3, 'Python': 1, 'Codding': 2}

Approach

  1. A dict comprehension maps each word to its vowel count.

Solution

Python
text = "We are Learning Python Codding"counts = {w: sum(ch in "aeiouAEIOU" for ch in w) for w in text.split()}print(counts)
Output
{'We': 1, 'are': 2, 'Learning': 3, 'Python': 1, 'Codding': 2}

Line by line

Line 2

ch in "aeiouAEIOU" is True or False; sum() counts the Trues.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Swap first and last letters of each word

Python Practice › String Programs › Program 12

Swap first and last letters of each word

EasyString Programs · 12 of 106

Write a Python program to exchange the first and last characters of every word in a string.

Input
"Its Online Learning"
Output
stI enlinO gearninL

Approach

  1. Split, swap each word, join again.

Solution

Python
def swap(word):    return word if len(word) < 2 else word[-1] + word[1:-1] + word[0] text = "Its Online Learning"print(" ".join(swap(w) for w in text.split()))
Output
stI enlinO gearninL

Line by line

Line 2

One-letter words are returned unchanged.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Swap the first and last characters

Python Practice › String Programs › Program 11

Swap the first and last characters

EasyString Programs · 11 of 106

Write a Python program to swap the first and last characters of a string.

Input
"SqaTool"
Output
lqaTooS

Approach

  1. Build last + middle + first.

Solution

Python
text = "SqaTool"swapped = text[-1] + text[1:-1] + text[0] if len(text) > 1 else textprint(swapped)
Output
lqaTooS

Line by line

Line 2

text[1:-1] is everything between the first and last characters.

Note

The original sample showed “IqaTooS” with a capital I, but swapping keeps the original letters, so the result is “lqaTooS”.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs