String CheatSheet
Complete Python String Cheatsheet with clear examples for quick revision
.replace(old, new)
Replaces all occurrences of the old substring with the new substring.
str1 = 'python is python and python is good.'
result = str1.replace('Python', 'java') # Note: case-sensitive
# result: 'python is python and python is good.' (no change due to case)Also:
str1 = 'python is python and python is good'
result = str1.replace('python', 'java', 2)
# 'java is java and python is good.'.split(separator)
Breaks a string into a list of substrings using the separator. Default separator is space.
str1 = 'python is a programming language'
result = str1.split() # ['python', 'is', 'a', 'programming', 'language']With maxsplit:
str1 = 'python is a programming language'
result = str1.split(' ', 2) # ['python', 'is', 'a programming language'].rsplit(separator)
Breaks a string into a list of substrings using the separator, starting from the right. Default separator is space.
str1 = 'python is a programming language'
result = str1.rsplit() # ['python', 'is', 'a', 'programming', 'language']With maxsplit:
str1 = 'python is a programming language'
result = str1.rsplit(' ', 2) # ['python is a', 'programming', 'language'].partition()
Splits the string at the first occurrence of the separator and includes the separator in the output.
str1 = 'python is a programming language'
result = str1.partition(' ') # ('python', ' ', 'is a programming language')Also:
str1 = 'python is a programming language'
result = str1.rpartition(' ') # ('python is a programming', ' ', 'language')String Formatting ( f" " )
Allows embedding variables directly inside strings using {}.
# Basic Example
name = "Ayush"
age = 61
print(f"My name is{name} and age is{age}") # My name is Ayush and my age is 61# Expression inside f-string
a = 10
b = 5
print(f"Sum is{a+b}")String Slicing
str1 = "Programming"Default Slicing:
str1[::] # 'Programming'Positive Index Slicing:
str1[0:6] # 'Progra'Negative Index Slicing:
Mixed Index Slicing:
Slicing with Step:
Reverse String (Negative Step):
Escape Characters
\n — New Line: Moves the cursor to the next line.
\t — Tab Space: Adds horizontal tab space (used for alignment).
\ — Backslash: Used to print a single backslash.
\' — Single Quote: Used to print a single quote inside single-quoted string.
\" — Double Quote: Used to print a double quote inside double-quoted string.
Last updated