Python String

Python program to check palindrome string

Description: Write a Python program to check whether a string is a palindrome.

Rules and hints:

  • A palindrome reads the same from both sides, like madam.
  • Ignore upper and lower case.

Python program to check a palindrome

def is_palindrome(text):
    text = text.lower()
    return text == text[::-1]

for word in ("madam", "Level", "python"):
    if is_palindrome(word):
        print(word, "is a palindrome")
    else:
        print(word, "is not a palindrome")

Output:

Tutorials Class - Output Window

madam is a palindrome
Level is a palindrome
python is not a palindrome

How it works

  • lower() changes the text to lowercase, so “Level” becomes “level”.
  • text[::-1] is the reversed string.
  • If the text equals its reverse, it is a palindrome.

Read about slicing in Python Strings.

Python program to count vowels in a string

Description: Write a Python program to count the number of vowels in a string.

Rules and hints:

  • Vowels are a, e, i, o and u.
  • Change the text to lowercase first, so capital letters are counted too.

Python program to count vowels

text = "Tutorials Class"
vowels = "aeiou"
count = 0

for ch in text.lower():
    if ch in vowels:
        count += 1

print("Number of vowels:", count)

Output:

Tutorials Class - Output Window

Number of vowels: 5

How it works

  • The loop checks each character of the text.
  • ch in vowels is True when the character is one of a, e, i, o, u.
  • The vowels in “Tutorials Class” are u, o, i, a and a, so the count is 5.

Python program to reverse a string

Description: Write a Python program to reverse a string in three different ways.

Rules and hints:

  • Strings are immutable, so you create a new string.

Python program to reverse a string

text = "Python"

# 1. slicing
print(text[::-1])

# 2. reversed() and join()
print("".join(reversed(text)))

# 3. loop
result = ""
for ch in text:
    result = ch + result
print(result)

Output:

Tutorials Class - Output Window

nohtyP
nohtyP
nohtyP

How it works

  • Slicing with step -1 goes through the string from the end.
  • reversed() gives the characters in reverse order, and join() makes a string again.
  • In the loop, every new character is added to the front of result.

Related: join() function.