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.
Now The Chapter starts!!
In Python, a string is a sequence of characters enclosed within either single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). You can’t mix single and double quotes in the same string or you’ll get a syntax error.
It is a case sensitive, non-mutable sequence of characters marked under quotation. It can contain alphabets, digits, white spaces and special characters.
Single quotes
my_string1 = ‘Hello, World!’
Double quotes
my_string2 = “Python Programming”
Triple quotes for multiline strings
my_string3 = ”’This is a
multiline
string.”’
Three pair of quotes are used when you have to define a multiline string or single quotes are part of string. A backslash ” can also be used to treat quotes as characters under string.
xyz = “Don’t Books Ram’s “
xyz = ‘Don’t Books Ram’s’
Behind the Stage— how string datatypes are stored in memory in Python and how assignment to variables works??
When a string is created in Python, the following happens in memory:
- Object Creation: A string object is created in memory to hold the string data.
- Character Storage: The individual characters of the string are stored contiguously in memory as a sequence of Unicode code points.
- Reference Counting: Python keeps track of how many references (variables or other objects) point to the string object.
When you assign a string to a variable, the following happens:
- Variable Creation: A variable is created in the current namespace (e.g., global or local).
- Reference Assignment: The variable is assigned a reference (a memory address) to the string object that was created earlier.
Key Points:
- The variable itself doesn’t store the string data directly; it simply holds a reference to the string object in memory.
- Multiple variables can refer to the same string object, and changing one variable won’t affect the others (because strings are immutable).
- When the reference count of a string object reaches zero (no variables or objects are pointing to it), the object is eligible for garbage collection and its memory is freed.
x=y=z="oh Boy"
or
x="oh Boy"
y=x
z=y
Both x = y = z = "oh Boy"
and x = "oh Boy"; y = x; z = y
achieve essentially the same result in Python, but with slightly different approaches. Let’s analyze them:
1. x = y = z = "oh Boy"
(Multiple Assignment)
- As explained earlier, this assigns the string “oh Boy” to all three variables (
x
,y
, andz
) simultaneously. They all become references to the same string object in memory.
2. x = "oh Boy"; y = x; z = y
(Sequential Assignment)
x = "oh Boy"
: First, the variablex
is assigned the string “oh Boy”.y = x
: Then, the value ofx
(which is the reference to the string “oh Boy”) is assigned toy
. Now, bothx
andy
point to the same string object.z = y
: Finally, the value ofy
(again, the reference to the string “oh Boy”) is assigned toz
. All three variables now reference the same string.
Key Difference
The primary difference lies in how the assignments are performed:
- Multiple assignment is a more concise way to assign the same value to multiple variables in a single step.
- Sequential assignment breaks down the process into individual steps, which can be useful for readability or if you need to perform additional operations between assignments.
Strings are immutable, meaning once they are created, their contents cannot be changed.
The error message “TypeError: ‘str’ object does not support item assignment” means you’re trying to change a character within a string using indexing. In Python, strings are immutable, meaning you can’t modify them directly after they’re created.
Few key things that make strings special in Python:
1. Immutability:
Unlike many other data types in Python where you can modify the contents of a variable, strings are immutable. This means that once a string is created, its content cannot be changed.
For instance:
message = "Hello, world!"
# Trying to modify a character
message[0] = 'X' # This will cause an error!
# You can reassign the variable to a new string
modified_message = 'X' + message[1:]
print(modified_message) # Output: Xello, world!
In this example, attempting to directly change the first character of message
results in an error. However, you can create a new string (modified_message
) by combining characters or using string methods like slicing.
s='RammaR'
s[2] ='e'
why it gives error?
The code s='RammaR'
s[2] ='e'
gives an error because strings in Python are immutable. This means you cannot change individual characters of a string in-place.
When you try to assign ‘e’ to s[2]
, you are attempting to modify the existing string object, which is not allowed.
To achieve a similar result, you would need to create a new string with the desired modification. For example:
s = 'RammaR'
s = s[:2] + 'e' + s[3:] # Replace the character at index 2 with 'e'
print(s) # Output: RameaR
if string in Python is immutable then how come
s=’RammaR’
s=s.replace(‘R’,’r’).lower() works
In Python, strings are immutable, meaning you can’t change the existing string object.
When you write s = s.replace('R', 'r').lower()
, you are not modifying the original string ‘RammaR’. Instead, you are creating a new string object with the replaced and lowercased characters and assigning it back to the variable s
. The original string ‘RammaR’ remains unchanged in memory, but the variable s
now points to the newly created string.
Here’s a step-by-step breakdown of what happens:
- Initial string:
s
is initially set to'RammaR'
. - Replacement operation:
s.replace('R', 'r')
creates a new string'rammar'
where all occurrences of'R'
are replaced with'r'
. - Lowercase operation:
.lower()
is called on'rammar'
, which converts it to'rammar'
(in this case, it remains the same because all characters are already lowercase). - Reassignment: The new string
'rammar'
is assigned back tos
.
The original string 'RammaR'
remains in memory until it is no longer referenced by any variable. Once there are no references to 'RammaR'
, it becomes eligible for garbage collection, meaning the memory can be reclaimed by the Python runtime. This process happens automatically, so you generally don’t need to worry about manually freeing memory.
If you want to ensure that the old string is no longer referenced, you can explicitly delete the reference using the del
statement:
del s
However, in this case, since s
is reassigned, the reference to the old string is already removed.
2. Sequence of Characters:
Strings are essentially ordered sequences of characters. Each character has its own index position, starting from 0. This allows you to access and manipulate individual characters or substrings within the string using indexing and slicing techniques.
3. Rich Set of Built-in Methods:
Python provides a comprehensive library of built-in string methods that empower you to perform various operations on strings. These methods cover aspects like:
- Case conversion (upper(), lower())
- Searching (find(), count())
- Modification (replace(), split(), join())
- Extraction (strip())
- Validation (isalnum(), isalpha())
These methods make string manipulation efficient and avoid the need to write complex loops or functions for common tasks.
4. Unicode Support:
Python strings are inherently unicode strings, meaning they can represent a wide range of characters from different languages and alphabets. This makes Python strings versatile for handling text data from various cultural contexts.
Head to Next
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.