Test your Python skills with Coding Exercises on string methods and formatting. Great for beginners learning Python strings through hands-on practice.
Topic: strings
Ask the user for their name and print: - The name in all uppercase - The name in all lowercase - The number of characters in the name
name = input("Enter your name: ")
Uppercase: JOHN
Lowercase: john
Length: 4
Given a string with leading and trailing spaces, remove them and print the cleaned sentence.
sentence = " Python is fun! "
Cleaned Sentence: Python is fun!
Align the word "Code" within a 20-character width using different alignments.
word = "Code"
Centered : Code
Left : Code
Right : Code
Perform slicing on the string "Python Programming": - Extract and print the first 6 characters - Extract and print the last 11 characters - Extract and print characters from index 7 to 17
text = "Python Programming"
First 6 characters: Python
Last 11 characters: Programming
Characters 7 to 17: Programming
Given name and age variables, print: "My name is Alice and I am 30 years old."
name = "Alice"
age = 30
My name is Alice and I am 30 years old.
Write a Python function `replace_second_occurrence(main_string, old_char, new_char)` - that replaces the second occurrence of `old_char` with `new_char` in `main_string`. - If `old_char` appears fewer than two times, the string should remain unchanged.
# Example 1: Basic replacement
main_string_1 = "hello world"
old_char_1 = "l"
new_char_1 = "X"
# Example 2: Another replacement
main_string_2 = "banana"
old_char_2 = "a"
new_char_2 = "Z"
# Example 3: Character appears only once
main_string_3 = "apple"
old_char_3 = "P" # Case sensitive, no match for 'P'
new_char_3 = "Q"
# Example 4: Character does not exist
main_string_4 = "test"
old_char_4 = "z"
new_char_4 = "Q"
Original: hello world, Old Char: l, New Char: X -> Result: helXo world
Original: banana, Old Char: a, New Char: Z -> Result: banZna
Original: apple, Old Char: P, New Char: Q -> Result: apple
Original: test, Old Char: z, New Char: Q -> Result: test
๐ ๐บ Watch the solution now!
Tutorials, Roadmaps, Bootcamps & Visualization Projects