Write program to display your name and perform following operations on it:
1. Display n characters from left. (Accept n as input from the user)
2. Count the number of vowels.
3. Reverse it.
My name is Joseph
# Program to perform operations on the name "Joseph Banjoko"
# Store the name in a variable
name = "Joseph Banjoko"
# Display the name
print ("Full Name:", name)
# Accept number of characters from user
n = int (input ("Enter the number of characters to display from left: "))
# Display first n characters using string slicing
# Syntax: string [start: end]
# It starts from index 0 and goes up to (n-1)
print("First", n, "characters:", name[:n])
# Count number of vowels
# Define vowels (both lowercase and uppercase)
vowels = "aeiouAEIOU"
vowel_count = 0
# Loop through each character in the string
for char in name:
if char in vowels:
vowel_count += 1
print("Number of vowels:", vowel_count)
# Reverse the string using slicing
# Syntax: string[::-1]
# It means start to end but step = -1 (reverse order)
reverse_name = name[::-1]
print("Reversed Name:", reverse_name)
I perform an extraction and printing operation on the first n characters of the name by using the
slicing function name[: n]. One of the most powerful features of Python is called slicing, and it
enables me to easily change different parts of the string.
A comparison of each character to the string vowels, which contains all of the vowels in both
lowercase and uppercase, is what I do in order to determine the number of vowels that are
contained in the name. In order to accomplish this, a generator expression is incorporated into
the sum () method. In this approach, you can quickly scan over the string and count the
characters based on the constraints that you specify.
The slice name[::-1] is what I use to turn the string around. This short way to reverse a string in
Python uses slicing. [::-1] tells Python to take the whole string and step backwards, which
changes the order of the characters.
Output
Full Name: Joseph Banjoko
Enter the number of characters to display from left: 6
First 6 characters: Joseph
Number of vowels: 5
Reversed Name: okojnaB hpesoJ
Conclusion
I have utilized fundamental Python principles in the process of developing this program. These
concepts include functions, slicing, conditional expressions, and loops. Each of these concepts
contributes to our comprehension of how to deal effectively with strings and user inputs. Not
only does this exercise correlate with the educational aims of learning iterations and string
operations in Python programming, but it also demonstrates how these concepts may be applied
in a practical setting.
References:
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.
Python Software Foundation. (2021). Python Language Reference, version 3.9 . Available at
[Link] . [Link]