String Data and Methods
✕Introduction to Strings
- Sequence of characters enclosed in single, double or triple quotes
- Single quotes is used when string contains double quotes and vice versa
- Triple quotes are used for multi-line strings
- Strings are immutable. i.e. once created, they cannot be changed in-place.
str_1 = "Hello, I'm learning Python!"str_2 = 'Ram said, "I have a pen."'str_3 = """Hello, World!"""
Examples:
Escaping Characters in Strings
- Use backslash (\) to escape special characters in strings
\n- Newline\t- Tab\\- Backslash\'- Single quote\"- Double quotestr_1 = 'Hello, I\'m learning Python!'str_2 = 'I have a pen.\nIt is good'str_3 = 'I have a pen.\\nIt is good'
Common escape sequences:
Examples:
String Methods
- Built-in functions that perform specific operations on strings and return a new string
- String are immutable. i.e. cannot be changed in-place.
- Position Related: Indexing, Slicing
- Generic: Concatenation, Repetition, Length
- Case Related:
isupper(),islower(),istitle(),upper(),lower(),title(),swapcase() - Data Check:
isalpha(),isdigit(),isalnum(),isspace(),startswith(),endswith() - Cleanup Related:
strip(),split(),join(),find(),index(),replace(),count()
Examples of string methods:
Indexing
- Used to extract a single character from a specific position of string
- Starts from 0, Negative indexing is also allowed
str_1 = "Python is fun"first_character= str_1[0] print(first_character)# Pprint(str_1[4])# oprint(str_1[-1])# nprint(str_1[7])# i
Examples:
Slicing
- Used to extract a substring from a string based on position
- Syntax:
variable[start:stop:step] - Start is inclusive, stop is exclusive, step is optional
str_1 = "Python is fun"substring = str_1[0:6] print(substring)# Pythonprint(str_1[0:6:2])#Ptoprint(str_1[:3])# Pytprint(str_1[10:])# funprint(str_1[::-1])# nuf si nohtyP
Examples:
Concatenation
- Used to combine two or more strings using
+operator str_1 = "Hello,"str_2 = "World!"greeting = str_1 + " " + str_2 print(greeting)# Hello, World!print("Python " + "is " + "fun!")# Python is fun!print(str_1 + " Python")# Hello, Python
Examples:
Repetition
- Used to repeat a string multiple times using
*operator str_1 = "Hello "repeated_str = str_1 * 3 print(repeated_str)# Hello Hello Helloprint("abc" * 5)# abcabcabcabcabc
Examples:
Length
- Used to get the number of characters in a string using
len()function str_1 = "Hello, World!"length = len(str_1) print(length)# 13print(len("Python"))# 6print(len("abc"))# 3
Examples:
Checking Case of String
- Used to check if characters in a string are uppercase, lowercase or title case
- All characters must be of same case for these methods to return True
str_1 = "Hello, World!"print(str_1.isupper())# Falseprint(str_1.islower())# Falseprint("PYTHON".isupper())# Trueprint("python".islower())# Trueprint("Hello".istitle())# True
Examples:
Case Conversion
- Used to change the case of characters in a string
str_1 = "Hello, World!"str_1_upper = str_1.upper()print(str_1_upper)# HELLO, WORLD!print(str_1.lower())# hello, world!print(str_1.title())# Hello, World!print(str_1.swapcase())# hELLO, wORLD!
Examples:
Checking value of String
- Used to check if characters in a string are alphabetic, numeric, alphanumeric, whitespace
str_1 = "Hello"print(str_1.isalpha())# Trueprint(str_1.isdigit())# Falseprint("123".isdigit())# Trueprint("abc123".isalnum())# Trueprint(" ".isspace())# Trueprint("Hello123".isalpha())# False
Examples:
startswith and endswith
- Used to check if a string starts or ends with a specific substring
str_1 = "2026-03-01.csv"print(str_1.startswith("2026"))# Trueprint(str_1.endswith(".pdf"))# Falseprint(str_1.startswith("03"))# False
Examples:
strip
- Used to remove leading and trailing whitespace (or other characters) from a string
lstripandrstripare used to remove leading and trailing characters respectivelystr_1 = " Hello, World! "stripped_str = str_1.strip()print(stripped_str)# "Hello, World!"print("###Data # Fun###".strip("#"))# "Data # Fun"print("###Data###".lstrip("#"))# "Data###"print("###Data###".rstrip("#"))# "###Data"
Examples:
split
- Used to split a string into a list of substrings based on a specified delimiter (default is whitespace)
str_1 = "Hello, World!"split_str = str_1.split()print(split_str)# ["Hello,", "World!"]print("2026-03-01.csv".split("-"))# ["2026", "03", "01.csv"]print("apple,banana,orange".split(","))# ["apple", "banana", "orange"]
Examples:
join
- Used to join a list of strings into a single string with a specified delimiter
str_list = ["Hello", "World"]joined_str = " ".join(str_list)print(joined_str)# "Hello World"print("-".join(["2026", "03", "01"]))# "2026-03-01"print(",".join(["apple", "banana", "orange"]))# "apple,banana,orange"print(".".join("apple"))# "a.p.p.l.e"
Examples:
find and index
- Used to find the index of the first occurrence of a specified substring in a string
.find()returns -1 butindex()raises an error if substring is not foundstr_1 = "Hello, World!"print(str_1.find("o"))# 4print(str_1.find("o"))# 4print(str_1.find("z"))# -1print(str_1.index("z"))# Raises ValueError
Examples:
replace
- Used to replace occurrences of a specified substring with another substring
str_1 = "Hello, World!"replaced_str = str_1.replace("World", "Python")print(replaced_str)# "Hello, Python!"print("2026-03-01.csv".replace("-", "/"))# "2026/03/01.csvprint("apple,banana,orange".replace(",", ";"))# "apple;banana;orange"
Examples:
count
- Used to count the number of occurrences of a specified substring in a string
str_1 = "Hello, World!"print(str_1.count("o"))# 2print("banana,apple".count("banana"))# 1print("2026-03-01.csv".count("-"))# 2print("test_exercise.py".count(".pdf"))# 0
Examples:
