Python Strings
Programming Fundamentals
October 15, 2025
Python Strings
What is a String?
A string is a group of characters (letters, numbers, or symbols).
Example:
"hello"
'Python'
"""This is a multiline string"""
You can use 'single', "double", or """triple""" quotes.
Accessing Characters in a String
You can get any character from a string by its position (index).
1. Positive Index (starts from 0)
name = "Python"
print(name[0]) # P
print(name[1]) # y
2. Negative Index (starts from -1)
print(name[-1]) # n (last letter)
print(name[-2]) # o
3. Slicing (get part of a string)
word = "Balochistan"
print(word[0:5]) # Baloch
print(word[:6]) # Baloch
print(word[2:]) # lochistan
Remember: the last index number is not included.
String Operators
Operator | What it Does | Example | Result |
---|---|---|---|
+ | Join two strings | "Hi" + "Python" | HiPython |
* | Repeat a string | "Hi" * 3 | HiHiHi |
βinβ and βnot inβ Operators
Used to check if a word is inside a string.
text = "University of Turbat"
print("Turbat" in text) # True
print("UOT" not in text) # True
In if condition:
if "Baloch" in text:
print("Found!")
else:
print("Not found!")
Useful String Functions
Function | What it Does | Example | Result |
---|---|---|---|
len() | Counts how many characters | len("Hello") | 5 |
chr() | Converts number β letter | chr(65) | 'A' |
ord() | Converts letter β number | ord('A') | 65 |
str() | Changes numbers β string | str(123) | '123' |
Strings Canβt Be Changed
Strings are immutable (cannot be changed).
word = "computer"
word[0] = "C" # Error
Common String Methods
Method | Meaning | Example | Result |
---|---|---|---|
upper() | All letters β BIG | "hello".upper() | 'HELLO' |
lower() | All letters β small | "HELLO".lower() | 'hello' |
capitalize() | First letter β BIG | "python".capitalize() | 'Python' |
title() | Each word β Big first letter | "my book".title() | 'My Book' |
count('a') | Count letters | "banana".count('a') | 3 |
find('a') | Find position | "data".find('t') | 2 |
strip() | Remove spaces | " hello ".strip() | 'hello' |
split() | Break into list | "a b c".split() | ['a','b','c'] |
isdigit() | Check only numbers | "123".isdigit() | True |
isalpha() | Check only letters | "abc".isalpha() | True |
isalnum() | Letters + numbers | "abc123".isalnum() | True |