A string is a sequence of characters enclosed in quotes. Strings can contain letters, numbers, spaces, and special characters.
# Using double quotes
message = "Hello, World!"
# Using single quotes
name = 'Alice'
# Using triple quotes for multi-line strings
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you!"""
Combine strings using the + operator:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
greeting = "Hello, " + name + "!"
print(greeting) # Output: Hello, Alice!
Repeat strings using the * operator:
star = "*"
print(star * 10) # Output: **********
word = "Ha"
print(word * 3) # Output: HaHaHa
Python provides many built-in methods for string manipulation:
text = "hello"
print(text.upper()) # Output: HELLO
text = "HELLO"
print(text.lower()) # Output: hello
text = "Python"
print(len(text)) # Output: 6
text = "I love Java"
new_text = text.replace("Java", "Python")
print(new_text) # Output: I love Python
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'orange']
Insert variables into strings using f-strings:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old"
print(message) # Output: My name is Alice and I am 25 years old
Special characters that have special meaning:
\n - Newline\t - Tab\\ - Backslash\' - Single quote\" - Double quoteprint("Line 1\nLine 2") # Output on two lines
print("Name\tAge") # Output with tab spacing
print("She said \"Hello\"") # Output: She said "Hello"
Create strings with your information, concatenate them, and use string methods to manipulate them!
Open Code Editor