Lesson: Working with Strings in Python
1. Creating Strings
In Python, text is called a string, and its data type is str.
You can create strings by enclosing text in either single (‘ ‘) or double (” “) quotes:
greeting = 'Hello'
place = "World"
message = greeting + ' ' + place # Output: "Hello World"
You can combine (concatenate) strings using the
+operator.
2. Handling Quotes and Special Characters
Sometimes, your string needs to contain quotes or backslashes. Python gives you three ways to handle this:
Use Opposite Quote Types:
text = "She said, 'G'day!'"
Escape Quotes with a Backslash :
text = 'She said, 'G'day!''
Use Raw Strings to Keep Backslashes Literal:
path = r'C:UsersFatimaDocuments'
3. Printing Text
Use print() to show strings on the screen.
s = 'Line one.nLine two.'
print(s)
Output:
Line one.
Line two.
nmeans a newline character. Python interprets it automatically.
4. Accessing Parts of Strings
Strings in Python are sequences — you can access characters by their index.
Indexing (Zero-Based)
word = 'Python'
print(word[0]) # 'P'
print(word[-1]) # 'n' (last character)
Slicing (start:stop)
word = 'Python'
part = word[1:4] # 'yth' (index 1 to 3)
start_to_mid = word[:2] # 'Py' (start to index 1)
mid_to_end = word[4:] # 'on' (index 4 to end)
Python slices always include the start index and exclude the stop index.
Quick Tips
| Concept | Example | Output |
|---|---|---|
| Concatenation | 'Hello' + ' World' |
'Hello World' |
| Escape characters | 'I'm happy' |
"I'm happy" |
| Newline | 'Line1nLine2' |
|
| Indexing | 'Python'[0] |
'P' |
| Slicing | 'Python'[1:4] |
'yth' |
