Here’s a comprehensive Python string function cheat sheet in tabular format:

FunctionSyntaxDescriptionExampleReturn Type
capitalizestr.capitalize()Capitalizes the first character of the string."hello".capitalize()"Hello"str
casefoldstr.casefold()Converts to lowercase, more aggressive than lower()."HELLO".casefold()"hello"str
centerstr.center(width, fillchar=' ')Centers the string, padded with fillchar."hello".center(10, '-')"--hello---"str
countstr.count(sub, start=0, end=len(str))Counts occurrences of sub in the string."hello world".count("o")2int
encodestr.encode(encoding, errors)Encodes the string to bytes."hello".encode("utf-8")b'hello'bytes
endswithstr.endswith(suffix, start, end)Checks if the string ends with the suffix."hello".endswith("o")Truebool
expandtabsstr.expandtabs(tabsize=8)Replaces tabs with spaces."hellotworld".expandtabs(4)"hello world"str
findstr.find(sub, start, end)Finds the first occurrence of sub. Returns -1 if not found."hello".find("e")1int
formatstr.format(*args, **kwargs)Formats the string using placeholders."Hello, {}!".format("World")"Hello, World!"str
format_mapstr.format_map(mapping)Formats the string using a mapping."Hello, {name}!".format_map({'name': 'World'})"Hello, World!"str
indexstr.index(sub, start, end)Like find(), but raises ValueError if not found."hello".index("e")1int
isalnumstr.isalnum()Checks if all characters are alphanumeric."abc123".isalnum()Truebool
isalphastr.isalpha()Checks if all characters are alphabetic."abc".isalpha()Truebool
isasciistr.isascii()Checks if all characters are ASCII."abc".isascii()Truebool
isdecimalstr.isdecimal()Checks if all characters are decimals."123".isdecimal()Truebool
isdigitstr.isdigit()Checks if all characters are digits."123".isdigit()Truebool
islowerstr.islower()Checks if all characters are lowercase."hello".islower()Truebool
isnumericstr.isnumeric()Checks if all characters are numeric."123".isnumeric()Truebool
isprintablestr.isprintable()Checks if all characters are printable."hellon".isprintable()Falsebool
isspacestr.isspace()Checks if all characters are whitespace." ".isspace()Truebool
istitlestr.istitle()Checks if the string is in title case."Hello World".istitle()Truebool
isupperstr.isupper()Checks if all characters are uppercase."HELLO".isupper()Truebool
joinstr.join(iterable)Joins elements of an iterable into a string." ".join(["hello", "world"])"hello world"str
ljuststr.ljust(width, fillchar=' ')Left-justifies the string, padded with fillchar."hello".ljust(10, '-')"hello-----"str
lowerstr.lower()Converts all characters to lowercase."HELLO".lower()"hello"str
lstripstr.lstrip([chars])Removes leading characters (whitespace by default)." hello".lstrip()"hello"str
maketransstr.maketrans(x, y, z)Creates a translation table.str.maketrans("abc", "123"){97: 49, 98: 50, 99: 51}dict
partitionstr.partition(sep)Splits the string into 3 parts around the separator."hello,world".partition(",")('hello', ',', 'world')tuple
replacestr.replace(old, new, count)Replaces occurrences of old with new."hello".replace("l", "x")"hexxo"str
rfindstr.rfind(sub, start, end)Finds the last occurrence of sub."hello".rfind("l")3int
rindexstr.rindex(sub, start, end)Like rfind(), but raises ValueError if not found."hello".rindex("l")3int
rjuststr.rjust(width, fillchar=' ')Right-justifies the string, padded with fillchar."hello".rjust(10, '-')"-----hello"str
rpartitionstr.rpartition(sep)Splits the string into 3 parts around the last occurrence of sep."hello,world".rpartition(",")('hello', ',', 'world')tuple
rsplitstr.rsplit(sep, maxsplit)Splits from the right, limits by maxsplit."a,b,c".rsplit(",", 1)['a,b', 'c']list
rstripstr.rstrip([chars])Removes trailing characters (whitespace by default)."hello ".rstrip()"hello"str
splitstr.split(sep, maxsplit)Splits the string into a list."a,b,c".split(",")['a', 'b', 'c']list
splitlinesstr.splitlines(keepends)Splits at line boundaries."hellonworld".splitlines()['hello', 'world']list
startswithstr.startswith(prefix, start, end)Checks if the string starts with prefix."hello".startswith("he")Truebool
stripstr.strip([chars])Removes leading and trailing characters." hello ".strip()"hello"str
swapcasestr.swapcase()Swaps case of all characters."Hello".swapcase()"hELLO"str
titlestr.title()Converts to title case."hello world".title()"Hello World"str
translatestr.translate(table)Translates string using table from maketrans."abc".translate({97: 49, 98: 50})"12c"str
upperstr.upper()Converts all characters to uppercase."hello".upper()"HELLO"str
zfillstr.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:

  1. Object Creation: A string object is created in memory to hold the string data.
  2. Character Storage: The individual characters of the string are stored contiguously in memory as a sequence of Unicode code points.
  3. 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:

  1. Variable Creation: A variable is created in the current namespace (e.g., global or local).
  2. 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 (xy, and z) 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 variable x is assigned the string “oh Boy”.
  • y = x: Then, the value of x (which is the reference to the string “oh Boy”) is assigned to y. Now, both x and y point to the same string object.
  • z = y: Finally, the value of y (again, the reference to the string “oh Boy”) is assigned to z. 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:

  1. Initial string: s is initially set to 'RammaR'.
  2. Replacement operation: s.replace('R', 'r') creates a new string 'rammar' where all occurrences of 'R' are replaced with 'r'.
  3. 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).
  4. Reassignment: The new string 'rammar' is assigned back to s.

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.

Pages ( 1 of 8 ): 1 23 ... 8Next »

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading