easycodelearning.com
🐍 Learn Python Online
Back to All Tutorials

Working with Strings

What is a String?

A string is a sequence of characters enclosed in quotes. Strings can contain letters, numbers, spaces, and special characters.

Creating Strings

# 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!"""

String Concatenation

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!

String Repetition

Repeat strings using the * operator:

star = "*"
print(star * 10)  # Output: **********

word = "Ha"
print(word * 3)  # Output: HaHaHa

String Methods

Python provides many built-in methods for string manipulation:

upper() - Convert to uppercase

text = "hello"
print(text.upper())  # Output: HELLO

lower() - Convert to lowercase

text = "HELLO"
print(text.lower())  # Output: hello

len() - Get string length

text = "Python"
print(len(text))  # Output: 6

replace() - Replace text

text = "I love Java"
new_text = text.replace("Java", "Python")
print(new_text)  # Output: I love Python

split() - Split string into list

text = "apple,banana,orange"
fruits = text.split(",")
print(fruits)  # Output: ['apple', 'banana', 'orange']

String Formatting

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

Escape Characters

Special characters that have special meaning:

  • \n - Newline
  • \t - Tab
  • \\ - Backslash
  • \' - Single quote
  • \" - Double quote

Examples:

print("Line 1\nLine 2")  # Output on two lines
print("Name\tAge")  # Output with tab spacing
print("She said \"Hello\"")  # Output: She said "Hello"

Key Takeaways

  • Strings are sequences of characters in quotes
  • Use + to concatenate strings
  • Use * to repeat strings
  • String methods help manipulate text
  • F-strings allow variable insertion
  • Escape characters create special formatting

Practice Time

Create strings with your information, concatenate them, and use string methods to manipulate them!

Open Code Editor
Next: Lists & Collections