Strings in Python

Strings are sequences of characters enclosed in quotes.
They are one of the most common data types in Python.

Why use strings?

  • Strings are used to store and manipulate text data.
  • They are essential for user input, messages, and data from files.
  • Useful for parsing, formatting, and displaying information.
  • Strings are widely used in web applications, reports, logs, and databases.

Examples of real-time usage:

  • Usernames or passwords: "Amit123"
  • Messages in a chat application: "Hello, how are you?"
  • File paths: "C:/Users/Documents/file.txt"
  • Displaying formatted reports: "Total sales: $2500"
  • Storing CSV or JSON data temporarily before processing

We will cover:

  1. Creating strings
  2. String indexing and slicing
  3. String methods
  4. String formatting
  5. Common operations
# ---- Example: creating strings ----
# Strings can be created using single, double, or triple quotes

str1 = "Hello"           # double quotes
str2 = 'Python'          # single quotes
str3 = """This is a 
multiline string"""      # triple quotes for multiple lines

print(str1)
print(str2)
print(str3)

Hello
Python
This is a
multiline string

Example: indexing and slicing

# ---- Example: indexing and slicing ----
# Each character has an index starting from 0
# Slicing allows extracting a part of the string

text = "Python"

print("First character:", text[0])       # P
print("Last character:", text[-1])       # n
print("Slice [0:4]:", text[0:4])         # characters 0 to 3 → 'Pyth'
print("Slice [2:]:", text[2:])           # characters from index 2 to end → 'thon'
print("Slice [:3]:", text[:3])           # first three characters → 'Pyt'

First character: P
Last character: n
Slice [0:4]: Pyth
Slice [2:]: thon
Slice [:3]: Pyt

Example: string methods

# ---- Example: string methods ----
# Useful built-in functions to manipulate strings

s = "python programming"

print("Uppercase:", s.upper())           # converts all letters to uppercase
print("Lowercase:", s.lower())           # converts all letters to lowercase
print("Title case:", s.title())          # capitalizes first letter of each word
print("Count 'p':", s.count('p'))        # counts occurrences of 'p'
print("Find 'program':", s.find('program'))  # returns starting index of substring
print("Replace 'python' with 'Java':", s.replace("python", "Java"))

Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Title case: Python Programming
Count ‘p’: 2
Find ‘program’: 7
Replace ‘python’ with ‘Java’: Java programming

Example: string formatting

# ---- Example: string formatting ----
# Combine variables and text in readable way

name = "Amit"
age = 25

# Using f-strings (Python 3.6+)
print(f"My name is {name} and I am {age} years old.")

# Using format() method
print("My name is {} and I am {} years old.".format(name, age))

# Using concatenation (less preferred)
print("My name is " + name + " and I am " + str(age) + " years old.")

My name is Amit and I am 25 years old.
My name is Amit and I am 25 years old.
My name is Amit and I am 25 years old.

Example: common string operations

# ---- Example: common string operations ----
s = "Python"

print("Length of string:", len(s))      # number of characters
print("Check if 'Py' in string:", "Py" in s)    # membership test
print("Repeat string:", s * 3)          # repeats string 3 times

Length of string: 6
Check if ‘Py’ in string: True
Repeat string: PythonPythonPython

Summary

We learned about strings in Python:

  • How to create strings using single, double, or triple quotes
  • Accessing characters with indexing and slicing
  • Common string methods: upper(), lower(), title(), count(), find(), replace()
  • Formatting strings: f-strings, format(), concatenation
  • Other operations: length, membership test, repetition

Next notebook: 02_lists.ipynb