PYTHON • Beginner

Python Strings

Strings are sequences of characters used to store text. In Python, strings are immutable — once created, they cannot be changed. You can create, slice, format, and manipulate strings using a rich set of built-in methods.

Creating a String

Strings can be created with single quotes, double quotes, or triple quotes.

name = "Ankit"
city = 'Varanasi'
address = """Shree Laxmi Narayan Complex
Ashapur Road
Varanasi - 221007"""

print(name)
print(city)

String Indexing

Each character has an index starting from 0. Negative indexing starts from the end (-1).

text = "PYTHON"

print(text[0])    # P
print(text[1])    # Y
print(text[-1])   # N
print(text[-2])   # O

String Slicing

Extract a portion using [start:end]. End index is not included.

text = "PYTHON"

print(text[0:3])     # PYT
print(text[2:])      # THON
print(text[:3])      # PYT
print(text[::2])     # PTO (every 2nd character)
print(text[::-1])    # NOHTYP (reversed)

String Length

text = "Hello Varanasi"
print(len(text))    # 14

Common String Methods

Python has dozens of built-in string methods. Here are the most used:

text = "  Hello World  "

print(text.upper())         # "  HELLO WORLD  "
print(text.lower())         # "  hello world  "
print(text.strip())         # "Hello World"
print(text.replace("World", "Varanasi"))   # "  Hello Varanasi  "
print(text.split())         # ['Hello', 'World']

name = "Ankit Kumar"
print(name.startswith("A"))    # True
print(name.endswith("r"))      # True
print(name.find("Kumar"))      # 6
print(name.count("a"))         # 1

String Concatenation

first = "Ankit"
last = "Kumar"

full = first + " " + last
print(full)    # Ankit Kumar

# Repeat
print("Hi " * 3)   # Hi Hi Hi

f-Strings (Formatted Strings)

f-strings are the modern, fastest, and most readable way to format strings. Introduced in Python 3.6.

name = "Ankit"
age = 22
city = "Varanasi"

print(f"My name is {name}, I'm {age}, from {city}.")

# With expressions
a = 10
b = 20
print(f"Sum of {a} and {b} is {a + b}")

# With formatting
price = 99.5
print(f"Price: ₹{price:.2f}")   # ₹99.50

Other Formatting Methods (Legacy)

# .format() method
print("Hello, {}. Welcome to {}.".format("Ankit", "Varanasi"))

# % formatting (very old)
print("Hello, %s. Age: %d" % ("Ankit", 22))
💡 Academy Tip

Always prefer f-strings over .format() or %. They're faster, cleaner, and support inline expressions. This is standard in modern Python code.

Escape Characters

print("Hello\nWorld")     # New line
print("Tab\there")        # Tab
print("She said \"Hi\"")  # Escape quotes
print("Path: C:\\Users")  # Backslash
📝 Try Yourself

Take a sentence as input from the user. Print: the sentence in UPPERCASE, its length, the first word, the last word, and the sentence reversed. Use slicing and string methods.

Quick Revision

  • Strings are immutable.
  • Created with single, double, or triple quotes.
  • Indexing starts at 0; negative from -1.
  • Slicing: [start:end:step].
  • Methods: upper, lower, strip, replace, split, find, count.
  • f-strings are the modern way to format strings.
  • Use \n, \t, \\ for special characters.

Interview Questions

Q: Are Python strings mutable or immutable?

A: Strings are immutable. You cannot change a character in place. Every string operation creates a new string. Example: s = "hi"; s[0] = "H" raises TypeError.

Q: What is an f-string and why is it preferred?

A: An f-string is a formatted string literal prefixed with f. It allows embedding expressions inside {}. It's preferred because it's faster, more readable, and supports inline expressions.

Q: Difference between find() and index()?

A: Both return the position of a substring. find() returns -1 if not found; index() raises a ValueError. Prefer find() when you want to handle "not found" gracefully.

Q: How do you reverse a string in Python?

A: Use slicing with step -1: text[::-1]. Example: "hello"[::-1] → "olleh".

Want to Master Python?

Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us