Here’s a comprehensive Python string function cheat sheet in tabular format:
Function | Syntax | Description | Example | Return Type |
---|---|---|---|---|
capitalize | str.capitalize() | Capitalizes the first character of the string. | "hello".capitalize() → "Hello" | str |
casefold | str.casefold() | Converts to lowercase, more aggressive than lower() . | "HELLO".casefold() → "hello" | str |
center | str.center(width, fillchar=' ') | Centers the string, padded with fillchar . | "hello".center(10, '-') → "--hello---" | str |
count | str.count(sub, start=0, end=len(str)) | Counts occurrences of sub in the string. | "hello world".count("o") → 2 | int |
encode | str.encode(encoding, errors) | Encodes the string to bytes. | "hello".encode("utf-8") → b'hello' | bytes |
endswith | str.endswith(suffix, start, end) | Checks if the string ends with the suffix . | "hello".endswith("o") → True | bool |
expandtabs | str.expandtabs(tabsize=8) | Replaces tabs with spaces. | "hellotworld".expandtabs(4) → "hello world" | str |
find | str.find(sub, start, end) | Finds the first occurrence of sub . Returns -1 if not found. | "hello".find("e") → 1 | int |
format | str.format(*args, **kwargs) | Formats the string using placeholders. | "Hello, {}!".format("World") → "Hello, World!" | str |
format_map | str.format_map(mapping) | Formats the string using a mapping. | "Hello, {name}!".format_map({'name': 'World'}) → "Hello, World!" | str |
index | str.index(sub, start, end) | Like find() , but raises ValueError if not found. | "hello".index("e") → 1 | int |
isalnum | str.isalnum() | Checks if all characters are alphanumeric. | "abc123".isalnum() → True | bool |
isalpha | str.isalpha() | Checks if all characters are alphabetic. | "abc".isalpha() → True | bool |
isascii | str.isascii() | Checks if all characters are ASCII. | "abc".isascii() → True | bool |
isdecimal | str.isdecimal() | Checks if all characters are decimals. | "123".isdecimal() → True | bool |
isdigit | str.isdigit() | Checks if all characters are digits. | "123".isdigit() → True | bool |
islower | str.islower() | Checks if all characters are lowercase. | "hello".islower() → True | bool |
isnumeric | str.isnumeric() | Checks if all characters are numeric. | "123".isnumeric() → True | bool |
isprintable | str.isprintable() | Checks if all characters are printable. | "hellon".isprintable() → False | bool |
isspace | str.isspace() | Checks if all characters are whitespace. | " ".isspace() → True | bool |
istitle | str.istitle() | Checks if the string is in title case. | "Hello World".istitle() → True | bool |
isupper | str.isupper() | Checks if all characters are uppercase. | "HELLO".isupper() → True | bool |
join | str.join(iterable) | Joins elements of an iterable into a string. | " ".join(["hello", "world"]) → "hello world" | str |
ljust | str.ljust(width, fillchar=' ') | Left-justifies the string, padded with fillchar . | "hello".ljust(10, '-') → "hello-----" | str |
lower | str.lower() | Converts all characters to lowercase. | "HELLO".lower() → "hello" | str |
lstrip | str.lstrip([chars]) | Removes leading characters (whitespace by default). | " hello".lstrip() → "hello" | str |
maketrans | str.maketrans(x, y, z) | Creates a translation table. | str.maketrans("abc", "123") → {97: 49, 98: 50, 99: 51} | dict |
partition | str.partition(sep) | Splits the string into 3 parts around the separator. | "hello,world".partition(",") → ('hello', ',', 'world') | tuple |
replace | str.replace(old, new, count) | Replaces occurrences of old with new . | "hello".replace("l", "x") → "hexxo" | str |
rfind | str.rfind(sub, start, end) | Finds the last occurrence of sub . | "hello".rfind("l") → 3 | int |
rindex | str.rindex(sub, start, end) | Like rfind() , but raises ValueError if not found. | "hello".rindex("l") → 3 | int |
rjust | str.rjust(width, fillchar=' ') | Right-justifies the string, padded with fillchar . | "hello".rjust(10, '-') → "-----hello" | str |
rpartition | str.rpartition(sep) | Splits the string into 3 parts around the last occurrence of sep . | "hello,world".rpartition(",") → ('hello', ',', 'world') | tuple |
rsplit | str.rsplit(sep, maxsplit) | Splits from the right, limits by maxsplit . | "a,b,c".rsplit(",", 1) → ['a,b', 'c'] | list |
rstrip | str.rstrip([chars]) | Removes trailing characters (whitespace by default). | "hello ".rstrip() → "hello" | str |
split | str.split(sep, maxsplit) | Splits the string into a list. | "a,b,c".split(",") → ['a', 'b', 'c'] | list |
splitlines | str.splitlines(keepends) | Splits at line boundaries. | "hellonworld".splitlines() → ['hello', 'world'] | list |
startswith | str.startswith(prefix, start, end) | Checks if the string starts with prefix . | "hello".startswith("he") → True | bool |
strip | str.strip([chars]) | Removes leading and trailing characters. | " hello ".strip() → "hello" | str |
swapcase | str.swapcase() | Swaps case of all characters. | "Hello".swapcase() → "hELLO" | str |
title | str.title() | Converts to title case. | "hello world".title() → "Hello World" | str |
translate | str.translate(table) | Translates string using table from maketrans . | "abc".translate({97: 49, 98: 50}) → "12c" | str |
upper | str.upper() | Converts all characters to uppercase. | "hello".upper() → "HELLO" | str |
zfill | str.zfill(width) | Pads with zeros to the left to reach the width. | "42".zfill(5) → "00042" | str |
This list includes all built-in string functions.
# Python Strings: A Comprehensive Guide
1. What is a String in Python?
A string in Python is a sequence of characters enclosed within single (' '
), double (" "
), or triple (''' '''
or """ """
) quotes.
🔹 Case-Sensitive & Immutable: Strings are case-sensitive and immutable, meaning once created, they cannot be changed.
🔹 Allowed Characters: Strings can contain alphabets, digits, spaces, and special characters.
Examples:
# Single Quotes
my_string1 = 'Hello, World!'
# Double Quotes
my_string2 = "Python Programming"
# Triple Quotes for Multiline Strings
my_string3 = '''This is a
multiline
string.'''
Why Use Triple Quotes?
🔹 To create multiline strings. 🔹 To include both single and double quotes within the string.
Example:
xyz = "Don't Books Ram's " # ✅ Correct
xyz = 'Don't Books Ram's' # ❌ Syntax Error
2. How Strings are Stored in Memory?
Behind the Scenes:
✅ Object Creation: A string object is created in memory. ✅ Character Storage: Stored as a sequence of Unicode code points. ✅ Reference Counting: Python tracks references to the string object. ✅ Variable Creation: A variable holds a reference to the string, not the data itself.
📌 Key Points: 🔹 Multiple variables can reference the same string. 🔹 Strings are immutable; modifying one variable won’t affect others. 🔹 When a string’s reference count drops to zero, it’s garbage collected.
Example:
x = y = z = "oh Boy" # Multiple Assignment
# Or
x = "oh Boy"
y = x
z = y
Both approaches reference the same string in memory.
3. String Immutability
Strings cannot be changed once created. Attempting to modify them directly results in an error:
message = "Hello, world!"
message[0] = 'X' # ❌ TypeError: 'str' object does not support item assignment
✅ Correct Way:
modified_message = 'X' + message[1:]
print(modified_message) # Output: Xello, world!
Example:
s = 'RammaR'
s[2] = 'e' # ❌ TypeError: Strings are immutable!
✅ Solution: Create a new string:
s = s[:2] + 'e' + s[3:]
print(s) # Output: RameaR
4. String Manipulation Techniques
Replace and Modify Strings
Even though strings are immutable, you can create new modified strings using built-in methods.
s = 'RammaR'
s = s.replace('R', 'r').lower()
print(s) # Output: 'rammar'
📌 What happens here? ✅ replace('R', 'r')
creates a new string 'rammar'
. ✅ .lower()
converts it to lowercase (remains 'rammar'
). ✅ The new string is assigned back to s
, while the old string is discarded.
If the old reference needs to be removed:
del s # Deletes the reference to the string
5. String as a Sequence of Characters
Strings are ordered sequences, and each character has an index position:
s = "Python"
print(s[0]) # Output: 'P'
print(s[-1]) # Output: 'n' (Negative Indexing)
✅ String Slicing:
s = "Programming"
print(s[0:4]) # Output: 'Prog' (Index 0 to 3)
print(s[:6]) # Output: 'Progra' (Start from 0)
print(s[4:]) # Output: 'ramming' (Till end)
6. Essential String Methods
Python provides built-in string methods for various operations:
Method | Description | Example |
---|---|---|
upper() | Converts to uppercase | 'hello'.upper() → 'HELLO' |
lower() | Converts to lowercase | 'HELLO'.lower() → 'hello' |
replace(old, new) | Replaces a substring | 'abc'.replace('a', 'x') → 'xbc' |
find(substring) | Finds index of substring | 'hello'.find('e') → 1 |
split(delimiter) | Splits into list | 'a,b,c'.split(',') → ['a', 'b', 'c'] |
join(iterable) | Joins elements into string | '-'.join(['a', 'b']) → 'a-b' |
strip() | Removes leading/trailing spaces | ' hello '.strip() → 'hello' |
count(substring) | Counts occurrences | 'banana'.count('a') → 3 |
7. Unicode Support in Strings
Python strings support Unicode, making them suitable for multiple languages.
s = "你好, мир, Hello!"
print(s)
Summary
✅ Strings are immutable, meaning modifications create new strings. ✅ Strings are stored in memory as objects, and variables hold references. ✅ Indexing & Slicing help extract and manipulate parts of strings. ✅ Built-in methods like replace()
, split()
, join()
, etc., make string manipulation easy. ✅ Python strings support Unicode, making them useful for international text processing.
By mastering these string operations, you can handle text data efficiently in Python! 🚀
Some commonly used string functions in Python:
- Conversion Functions:
upper()
: Converts all characters in the string to uppercase.lower()
: Converts all characters in the string to lowercase.capitalize()
: Capitalizes the first character of the string.title()
: Converts the first character of each word to uppercase.
- Search and Replace Functions:
find(substring)
: Returns the lowest index in the string where substring is found.rfind(substring)
: Returns the highest index in the string where substring is found.index(substring)
: Like find(), but raises ValueError if the substring is not found.rindex(substring)
: Like rfind(), but raises ValueError if the substring is not found.count(substring)
: Returns the number of occurrences of substring in the string.replace(old, new)
: Returns a copy of the string with all occurrences of substring old replaced by new.
- Substring Functions:
startswith(prefix)
: Returns True if the string starts with the specified prefix, otherwise False.endswith(suffix)
: Returns True if the string ends with the specified suffix, otherwise False.strip()
: Removes leading and trailing whitespace.lstrip()
: Removes leading whitespace.rstrip()
: Removes trailing whitespace.split(sep)
: Splits the string into a list of substrings using the specified separator.rsplit(sep)
: Splits the string from the right end.partition(sep)
: Splits the string into three parts using the specified separator. Returns a tuple with (head, separator, tail).rpartition(sep)
: Splits the string from the right end.
- String Formatting Functions:
format()
: Formats the string.join(iterable)
: Concatenates each element of the iterable (such as a list) to the string.
- String Testing Functions:
isalpha()
: Returns True if all characters in the string are alphabetic.isdigit()
: Returns True if all characters in the string are digits.isalnum()
: Returns True if all characters in the string are alphanumeric (letters or numbers).isspace()
: Returns True if all characters in the string are whitespace.
- Miscellaneous Functions:
len()
: Returns the length of the string.ord()
: Returns the Unicode code point of a character.chr()
: Returns the character that corresponds to the Unicode code point.
Looping over a String
Strings are objects that contain a sequence of single-character strings.
A single letter is classified as a string in Python. For example, string[0] is considered a string even though it is just a single character.
Here’s how you can do it-Loooping Over a String:
my_string = "Hello, World!"
for char in my_string:
print(char)
In Python, you can use a for loop to iterate over each character in a string. To loop over a string means to start with the first character in a string(Position 0) and iterate over each character until the end of the string( Position- Length-1).
#to get commonLetters from two string with case and duplicates ignored and the result #sorted /Or Not sorted alpabetically
def commonLetters(str1,str2):
common = ""
for i in str1:
if i in str2 and i not in common:
common += i
return "".join(sorted(common))
def commonLettersnosort(str1,str2):
common = ""
for i in str1:
if i in str2 and i not in common:
common += i
return "".join(common)
def commonLettersnosortnocase(str1,str2):
common = ""
for i in str1:
if i.upper() in str2.upper() and i not in common:
common += i
return "".join(common)
Check for -
commonLettersnosort('shyam','Ghanshyam') commonLettersnosortnocase('shyam','GhanShYam')
Slicing Strings:
You can slice strings using the syntax [start:stop:step]
, where:
start
: The starting index of the slice (inclusive).stop
: The ending index of the slice (exclusive).step
: The step or increment between characters (optional).
If you try to access an index that’s larger than the length of your string, you’ll get an IndexError. This is because you’re trying to access something that doesn’t exist!
You can also access indexes from the end of the string going towards the start of the string by using negative values. The index [-1] would access the last character of the string, and the index [-2] would access the second-to-last character.
Example:
my_string = "Python Programming"
# Slicing from index 7 to the end
substring1 = my_string[7:]
print(substring1) # Output: Programming
# Slicing from index 0 to 6
substring2 = my_string[:6]
print(substring2) # Output: Python
# Slicing from index 7 to 13 with step 2
substring3 = my_string[7:13:2]
print(substring3) # Output: Porm
string1 = "Greetings, Earthlings"
print(string1[0]) # Prints “G”
print(string1[4:8]) # Prints “ting”
print(string1[11:]) # Prints “Earthlings”
print(string1[:5]) # Prints “Greet”
If your index is beyond the end of the string, Python returns an empty string.
An optional way to slice an index is by the stride argument, indicated by using a double colon.
This allows you to skip over the corresponding number of characters in your index, or if you’re using a negative stride, the string prints backwards.
print(string1[0::2]) # Prints “Getns atlns”
print(string1[::-1]) # Prints “sgnilhtraE ,sgniteerG”
Using the str.format()
method String Formatting
The str.format()
method is a powerful tool in Python for string formatting. It allows you to create dynamic strings by inserting values into placeholders within a string template. Here’s a basic overview of how it works:
Basic Usage:
You start with a string containing placeholder curly braces {}
where you want to insert values, and then you call the format()
method on that string with the values you want to insert.
Example:
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
My name is John and I am 30 years old.
Positional Arguments:
You can pass values to the format()
method in the order that corresponds to the order of the placeholders in the string.
Example:
print("My name is {} and I am {} years old.".format("Alice", 25))
My name is Alice and I am 25 years old.
Keyword Arguments:
Alternatively, you can pass values using keyword arguments, where the keys match the names of the placeholders.
Example:
print("My name is {name} and I am {age} years old.".format(name="Bob", age=28))
Output:
My name is Bob and I am 28 years old.
Formatting:
You can also specify formatting options within the placeholders to control the appearance of the inserted values, such as precision for floating-point numbers or padding for strings.
Example:
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
Output:
The value of pi is 3.14
Padding and Alignment:-
You can align strings and pad them with spaces or other characters.
left_aligned = "{:<10}".format("left")
right_aligned = "{:>10}".format("right")
center_aligned = "{:^10}".format("center")
print(left_aligned)
print(right_aligned)
print(center_aligned)
Accessing Arguments by Position:
You can access arguments out of order and even multiple times by specifying their positions within the curly braces.
Example:
print("{1} {0} {1}".format("be", "or", "not"))
Output:
or be or
Guess the ERROR:-

Head to Next
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.