Strings
A string is a sequence of characters. Text is the most common kind of data you will handle, so it is worth knowing strings well.
Creating strings
Single and double quotes are equivalent. Pick one and be consistent; switch when the string itself contains a quote.
a = "Hello"
b = 'World'
c = "It's a nice day"
d = 'She said "hi"'
print(a, b, c, d)Triple quotes create multi line strings:
poem = """Roses are red,
violets are blue."""
print(poem)Escape characters
A backslash gives the next character a special meaning.
print("Line one\nLine two") # newline
print("Column A\tColumn B") # tab
print("She said \"hi\"") # a literal quote
print("C:\\Users\\Priya") # a literal backslashRaw strings turn escapes off, which is handy for file paths and regular expressions:
print(r"C:\Users\Priya\new_folder")Length
word = "machine"
print(len(word))Indexing
Each character has a position, starting at 0. Negative indices count from the end.
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[-1]) # n
print(word[-2]) # oSlicing
word[start:stop] returns the characters from start up to but not including stop. Leave either side blank to mean "from the beginning" or "to the end".
word = "Python"
print(word[0:3]) # Pyt
print(word[:3]) # Pyt
print(word[3:]) # hon
print(word[-3:]) # hon
print(word[::2]) # Pto, every second character
print(word[::-1]) # nohtyP, reversedStrings are immutable
You cannot change a character in place. Build a new string instead.
word = "cat"
# word[0] = "b" would raise TypeError
word = "b" + word[1:]
print(word)Concatenation and repetition
first = "Indus"
second = "AI"
print(first + second)
print(first + " " + second)
print("-" * 20)Checking contents
sentence = "The quick brown fox"
print("quick" in sentence)
print("slow" not in sentence)Looping through a string
for ch in "abc":
print(ch)Practice
- Store your full name in a variable and print it reversed.
- Extract just the year from the string
"2026-09-15"using a slice. - Print a line of 30 equals signs without typing 30 characters.
