Python String Exercise-1

Here’s an exercise for beginners on creating and manipulating strings in Python:

  1. Create a variable called name and assign it a string value representing your name.
  2. Use the len() function to find the length of your name and assign the result to a variable called name_length.
  3. 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 and name_length into a single string.
  4. Create a new variable called favorite_food and assign it a string value representing your favorite food.
  5. Use string formatting to print a message to the console that says “I love to eat [favorite_food]!”.
  6. Use the split() method to split the value of favorite_food into a list of words and assign the result to a variable called food_list.
  7. Print the first word in food_list to the console.
  8. Use the join() method to combine the words in food_list into a single string, separated by commas, and assign the result to a variable called food_string.
  9. 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:

  1. Create a variable called word and assign it a string value representing a word of your choice.
  2. Print the length of the word to the console using the len() function.
  3. Use string indexing to print the first character of the word to the console.
  4. Use string slicing to print the first three characters of the word to the console.
  5. Use string slicing to print the last three characters of the word to the console.
  6. Use string slicing to print every other character of the word, starting from the second character, to the console.
  7. Use the in keyword to check if the letter “e” is in the word. Print the result to the console.
  8. 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.
  9. 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

 

 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved