Back to Lessons
BeginnerBasics

String Fun

lesson_04.py
>>> # String Fun ## Concept Strings are pieces of text in Python and are used whenever you need to handle words or phrases. A string in Python is created by enclosing characters in either single (`'`) or double (`"`) quotes. Here’s an example: ```python # Creating a string name = "Alice" message = 'Hello, this is a string!' ``` You can combine, or concatenate, strings using the `+` operator. This technique allows you to create more complex text messages by joining smaller strings together: ```python # Concatenating strings first = "Hello" second = "World" result = first + " " + second print(result) # Outputs: Hello World ``` To avoid common mistakes, remember that you can't directly concatenate a string and a number unless you first convert the number to a string using the `str()` function: ```python # Correcting string and number concatenation age = 10 message = "I am " + str(age) print(message) # Outputs: I am 10 ``` ## Practice Now, it's time for some hands-on practice! Your task is to create a simple program that defines a string and combines it into a sentence. Follow these steps closely: 1. Create a variable called `favorite_color` and set it equal to a string representing your favorite color. 2. Use string concatenation to create a new string that says, "My favorite color is " along with the color you chose. 3. Print this message. Here's a template to get you started: ```python favorite_color = "blue" # ← Replace "blue" with your favorite color print("My favorite color is " + favorite_color) ``` Make the necessary change to ensure the message is printed as expected and matches the provided test case output. Once your program runs successfully, it should print: ``` My favorite color is blue ```
Code Editor

Sign in to submit your answer and earn XP.