Python Basics — String Creation & Indexing
String Creation & Indexing
Strings are sequences of characters. Python provides multiple ways to create them and powerful tools to access individual characters.
String Creation Methods
Single and Double Quotes
name = 'Alice'
greeting = "Hello, World!"
# Both are identical
print(type(name)) # <class 'str'>
print(type(greeting)) # <class 'str'>
Use single quotes when the string contains double quotes, and vice versa:
quote = 'She said "hello"'
html = "<p class='main'>Text</p>"
Triple Quotes (Multi-Line Strings)
message = """This is a
multi-line
string."""
print(message)
Output:
This is a
multi-line
string.
Triple quotes preserve line breaks and are also used for docstrings.
Empty Strings
empty = ""
also_empty = str()
print(len(empty)) # 0
print(bool(empty)) # False (empty string is falsy)
print(bool("hello")) # True (non-empty string is truthy)
Positive and Negative Indexing
Every character in a string has an index position. Python supports both positive (left-to-right) and negative (right-to-left) indexing:
String: P y t h o n
Index: 0 1 2 3 4 5
Neg: -6 -5 -4 -3 -2 -1
word = "Python"
# Positive indexing (starts at 0)
print(word[0]) # P
print(word[1]) # y
print(word[5]) # n
# Negative indexing (starts at -1)
print(word[-1]) # n
print(word[-2]) # o
print(word[-6]) # P
IndexError
Accessing an index that doesn’t exist raises an error:
word = "Python"
# print(word[10]) # IndexError: string index out of range
String Length with len()
message = "Hello, World!"
print(len(message)) # 13
empty = ""
print(len(empty)) # 0
Spaces, punctuation, and special characters all count:
print(len("a b")) # 3 (includes the space)
print(len("\t\n")) # 2 (tab + newline)
Iterating Over Strings
word = "Hello"
for char in word:
print(char, end=" ")
Output:
H e l l o
With enumerate():
word = "Hello"
for index, char in enumerate(word):
print(f"Index {index}: '{char}'")
Output:
Index 0: 'H'
Index 1: 'e'
Index 2: 'l'
Index 3: 'l'
Index 4: 'o'
Escape Characters
| Escape | Description | Example | Output |
|---|---|---|---|
\n |
Newline | "a\nb" |
a(newline)b |
\t |
Tab | "a\tb" |
a(tab)b |
\\ |
Backslash | "a\\b" |
a\b |
\' |
Single quote | 'it\'s' |
it’s |
\" |
Double quote | "say \"hi\"" |
say “hi” |
print("First\nSecond")
print("Column1\tColumn2")
print("Path: C:\\Users\\docs")
Output:
First
Second
Column1 Column2
Path: C:\Users\docs
Raw Strings
Prefix with r to ignore escape characters:
# Normal string
print("C:\new\folder") # C: (newline) ew (tab) older
# Raw string
print(r"C:\new\folder") # C:\new\folder
Raw strings are essential for:
- Windows file paths
- Regular expressions
- Any string with lots of backslashes
String Immutability
Strings cannot be changed in place:
word = "Python"
# word[0] = "J" # TypeError: 'str' object does not support item assignment
To “modify” a string, create a new one:
word = "Python"
new_word = "J" + word[1:]
print(new_word) # Jython
String Concatenation and Repetition
# Concatenation with +
first = "Hello"
second = "World"
combined = first + ", " + second + "!"
print(combined) # Hello, World!
# Repetition with *
line = "-" * 30
print(line) # ------------------------------
# Implicit concatenation (adjacent string literals)
message = "Hello " "World"
print(message) # Hello World
Membership Testing
message = "Hello, World!"
print("Hello" in message) # True
print("hello" in message) # False (case-sensitive)
print("xyz" not in message) # True
Summary
- Create strings with
'single',"double", or"""triple"""quotes - Access characters with positive (
[0]) or negative ([-1]) indexing - Use
len()to get string length - Escape characters:
\n,\t,\\,\',\" - Raw strings (
r"...") ignore escape sequences - Strings are immutable — operations create new strings
- Use
into check if a substring exists
Next up: String Slicing →