indusai.co

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.

python
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:

python
poem = """Roses are red,
violets are blue."""
print(poem)

Escape characters

A backslash gives the next character a special meaning.

python
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 backslash

Raw strings turn escapes off, which is handy for file paths and regular expressions:

python
print(r"C:\Users\Priya\new_folder")

Length

python
word = "machine"
print(len(word))

Indexing

Each character has a position, starting at 0. Negative indices count from the end.

python
word = "Python"
print(word[0])    # P
print(word[1])    # y
print(word[-1])   # n
print(word[-2])   # o

Slicing

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".

python
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, reversed

Strings are immutable

You cannot change a character in place. Build a new string instead.

python
word = "cat"
# word[0] = "b"   would raise TypeError
word = "b" + word[1:]
print(word)

Concatenation and repetition

python
first = "Indus"
second = "AI"
print(first + second)
print(first + " " + second)
print("-" * 20)

Checking contents

python
sentence = "The quick brown fox"
print("quick" in sentence)
print("slow" not in sentence)

Looping through a string

python
for ch in "abc":
    print(ch)

Practice

  1. Store your full name in a variable and print it reversed.
  2. Extract just the year from the string "2026-09-15" using a slice.
  3. Print a line of 30 equals signs without typing 30 characters.