Python String Exercise-1
Here’s an exercise for beginners on creating and manipulating strings in Python:
- Create a variable called
name
and assign it a string value representing your name. - Use the
len()
function to find the length of your name and assign the result to a variable calledname_length
. - Print a message to the console that says “My name is [name] and it has [name_length] letters.” Use string concatenation to combine the values of
name
andname_length
into a single string. - Create a new variable called
favorite_food
and assign it a string value representing your favorite food. - Use string formatting to print a message to the console that says “I love to eat [favorite_food]!”.
- Use the
split()
method to split the value offavorite_food
into a list of words and assign the result to a variable calledfood_list
. - Print the first word in
food_list
to the console. - Use the
join()
method to combine the words infood_list
into a single string, separated by commas, and assign the result to a variable calledfood_string
. - Print
food_string
to the console.
Solution:
# Step 1 name = "John" # Step 2 name_length = len(name) # Step 3 print("My name is " + name + " and it has " + str(name_length) + " letters.") # Step 4 favorite_food = "pizza" # Step 5 print("I love to eat {}!".format(favorite_food)) # Step 6 food_list = favorite_food.split() # Step 7 print(food_list[0]) # Step 8 food_string = ", ".join(food_list) # Step 9 print(food_string)
Python String Exercise-2
here’s another exercise on strings in Python for beginners:
- Create a variable called
word
and assign it a string value representing a word of your choice. - Print the length of the word to the console using the
len()
function. - Use string indexing to print the first character of the word to the console.
- Use string slicing to print the first three characters of the word to the console.
- Use string slicing to print the last three characters of the word to the console.
- Use string slicing to print every other character of the word, starting from the second character, to the console.
- Use the
in
keyword to check if the letter “e” is in the word. Print the result to the console. - Use string concatenation and repetition to create a new string that repeats the word three times, separated by spaces, and assign it to a variable called
new_word
. - Print
new_word
to the console.
Solution:
# Step 1 word = "python" # Step 2 print(len(word)) # Step 3 print(word[0]) # Step 4 print(word[:3]) # Step 5 print(word[-3:]) # Step 6 print(word[1::2]) # Step 7 if "e" in word: print("The letter 'e' is in the word.") else: print("The letter 'e' is not in the word.") # Step 8 new_word = word + " " + word + " " + word print(new_word) # Step 9