String CheatSheet

Memory Allocation in Python With Example

Sure, let's take a look at an example of memory allocation in Python.

a = 10
b = 20
c = a + b

In this example, we are creating three variables a, b, and c, and assigning them values. The Python interpreter will automatically allocate memory to store the values of these variables.

When we assign a the value 10, the Python interpreter allocates memory to store an integer object with the value 10. Similarly, when we assign b the value 20, the Python interpreter allocates memory to store another integer object with the value 20.

When we execute the statement c = a + b, Python creates a new integer object with the value 30 and allocates memory to store it. It then assigns the memory address of this new object to the variable c.

We can use the id() function in Python to get the memory address of an object. For example:

print(id(a)) # prints the memory address of the integer object with value 10
print(id(b)) # prints the memory address of the integer object with value 20
print(id(c)) # prints the memory address of the integer object with value 30

This will output something like:

140730954963376
140730954963696
140730954963376

Notice that a and c have the same memory address, while b has a different memory address. This is because a and c are pointing to the same integer object with value 10, while b is pointing to a different integer object with value 20.

What if we change value of a

If we change the value of a, Python will create a new integer object with the new value and allocate memory to store it. For example:

a = 10
print(id(a)) # prints the memory address of the integer object with value 10

a = 5
print(id(a)) # prints the memory address of the integer object with value 5

This will output something like:

140730954963376
140730954963216

Notice that the memory address of a changed after we changed its value from 10 to 5. This is because Python allocated new memory to store the new integer object with the value 5.

It's worth noting that Python uses a technique called interned strings for small integers (-5 to 256) and some string objects. This means that Python will reuse the same memory address for these objects to save memory. So, in some cases, changing the value of an object may not result in a new memory allocation. However, this behavior is implementation-specific and may vary depending on the Python interpreter being used.

what if all Variables are reffering to same value

If all variables are referring to the same value, then they will have the same memory address. For example:

a = 10
b = 10
c = a

print(id(a)) # prints the memory address of the integer object with value 10
print(id(b)) # prints the same memory address as a
print(id(c)) # prints the same memory address as a

This will output something like:

140730954963376
140730954963376
140730954963376

Notice that a, b, and c all have the same memory address. This is because they are all pointing to the same integer object with the value 10.

Python automatically optimizes the memory allocation for immutable objects, such as integers and strings, by using a technique called interning. When we create multiple variables that have the same value, Python will reuse the same object to save memory.

However, this behavior is implementation-specific and may vary depending on the Python interpreter being used. Additionally, for mutable objects, such as lists and dictionaries, multiple variables pointing to the same object can have unexpected consequences.

Strings CheatSheet

Difference In Quotes in Python String With Example

In Python, there are two types of quotes that can be used to define a string: single quotes (') and double quotes (").

Both types of quotes can be used interchangeably to define a string, but there are some differences in how they behave in certain situations.

One difference is that if a string contains a quote character, it may be more convenient to use the other type of quote to define the string in order to avoid having to escape the quote character with a backslash. For example:

print("She said, 'Hello!'") # prints: She said, 'Hello!'
print('He said, "Hi!"')    # prints: He said, "Hi!"

Another difference is that triple-quoted strings can be used to define multi-line strings. Triple-quoted strings can be defined using either single or double quotes, but if the string itself contains single or double quotes, it may be more convenient to use the other type of quote to define the string. For example:

multi_line_str = """This is a
multi-line
string."""
print(multi_line_str) # prints:
# This is a
# multi-line
# string.

multi_line_str2 = '''He said, "I don't know"'''
print(multi_line_str2) # prints: He said, "I don't know"

In general, the choice between single or double quotes is a matter of personal preference or code style. Some programmers prefer to use one type of quote over the other for consistency, while others may switch between them depending on the situation.

String Indexing and Slicing in Python CheetSheat

String:         H   e   l   l   o   ,       w   o   r   l   d   !
Positive index: 0   1   2   3   4   5       6   7   8   9   10  11
Negative index: -12 -11 -10 -9  -8  -7      -6  -5  -4  -3  -2  -1

To access a specific character in a string, you can use indexing. The index of the first character in the string is 0, and the index of the last character is -1. To access a character at a specific index, use square brackets with the index inside them. For example:

phpCopy codestring = "Hello, world!"
print(string[0])  # H
print(string[6])  # ,
print(string[-1]) # !

To extract a slice of a string, you can use slicing. Slicing allows you to extract a portion of a string by specifying a starting index, an ending index, and an optional step size. To slice a string, use square brackets with the starting index, ending index, and step size separated by colons. For example:

string = "Hello, world!"
print(string[0:5])    # Hello
print(string[7:])     # world!
print(string[:5])     # Hello
print(string[::2])    # Hlo ol!
print(string[::-1])   # !dlrow ,olleH

In the above examples, string[0:5] returns a slice that includes characters from index 0 up to, but not including, index 5 (i.e., H e l l o). string[7:] returns a slice that includes characters from index 7 to the end of the string (i.e., w o r l d !). string[:5] returns a slice that includes characters from the beginning of the string up to, but not including, index 5 (i.e., H e l l o). string[::2] returns a slice that includes every second character of the string (i.e., H l o o !). string[::-1] returns a slice that includes all characters of the string in reverse order (i.e., ! d l r o w , o l l e H).

Len Max and min Function In String

In Python, the len() function is used to get the length of a string, while the max() and min() functions are used to get the maximum and minimum characters in a string, respectively.

Here's how you can use these functions:

string = "hello world"

# len()
print(len(string))   # Output: 11

# max()
print(max(string))   # Output: w

# min()
print(min(string))   # Output: ' '

In the example above, len(string) returns the length of the string string, which is 11.

max(string) returns the maximum character in string, which in this case is w, because w comes after all the other characters in the ASCII table.

min(string) returns the minimum character in string, which is a space (' '), because it comes before all the other characters in the ASCII table.

String Methods

  1. capitalize() - Converts the first character of the string to uppercase.

  2. casefold() - Returns a lowercase string, suitable for case-insensitive comparisons.

  3. center(width, fillchar) - Returns a centered string of length width. Padding is done using the specified fill character.

  4. count(substring, start, end) - Returns the number of occurrences of substring in the string, optionally restricting the search to the specified start and end indices.

  5. endswith(suffix, start, end) - Returns True if the string ends with the specified suffix, optionally restricting the search to the specified start and end indices.

  6. find(substring, start, end) - Returns the index of the first occurrence of substring in the string, optionally restricting the search to the specified start and end indices. Returns -1 if the substring is not found.

  7. index(substring, start, end) - Similar to find(), but raises an exception if the substring is not found.

  8. isalnum() - Returns True if all characters in the string are alphanumeric (i.e. letters or digits).

  9. isalpha() - Returns True if all characters in the string are alphabetic (i.e. letters).

  10. isdecimal() - Returns True if all characters in the string are decimal (i.e. digits).

  11. isdigit() - Returns True if all characters in the string are digits.

  12. isidentifier() - Returns True if the string is a valid identifier (i.e. a variable name).

  13. islower() - Returns True if all cased characters in the string are lowercase.

  14. isnumeric() - Returns True if all characters in the string are numeric (i.e. digits or numeric characters in other scripts).

  15. isprintable() - Returns True if all characters in the string are printable (i.e. not control characters).

  16. isspace() - Returns True if all characters in the string are whitespace.

  17. istitle() - Returns True if the string is in titlecase (i.e. the first character of each word is uppercase and the rest are lowercase).

  18. isupper() - Returns True if all cased characters in the string are uppercase.

  19. join(iterable) - Joins the elements of an iterable (e.g. a list) into a single string, separated by the string on which the method is called.

  20. ljust(width, fillchar) - Returns a left-justified string of length width. Padding is done using the specified fill character.

  21. lower() - Returns a lowercase version of the string.

  22. lstrip(chars) - Returns a copy of the string with leading whitespace (or other characters specified by the chars parameter) removed.

  23. partition(separator) - Returns a tuple containing three elements: the substring before the first occurrence of the separator, the separator itself, and the substring after the separator.

  24. replace(old, new, count) - Returns a copy of the string with all occurrences of the old substring replaced by the new substring. The count parameter specifies the maximum number of replacements to make (defaults to all occurrences).

  25. rfind(substring, start, end) - Same as find(), but searches from the right end of the string.

  26. rindex(substring, start, end) - Same as index(), but searches from the right end of the string.

  27. rjust(width, fillchar) - Returns a right-justified string of length width. Padding is done using the specified fill character.

  28. rpartition(separator) - Same as partition but with right side.

  29. rsplit(sep=None, maxsplit=-1) - Splits the string into a list of substrings from the right end, using the specified separator. The maxsplit parameter limits the number of splits that occur.

  30. rstrip(chars) - Returns a copy of the string with trailing whitespace (or other characters specified by the chars parameter) removed.

  31. split(sep=None, maxsplit=-1) - Splits the string into a list of substrings, using the specified separator. The maxsplit parameter limits the number of splits that occur.

  32. splitlines(keepends=False) - Splits the string at line breaks and returns a list of lines. The keepends parameter determines whether the line break characters should be included in the resulting lines.

  33. startswith(prefix, start, end) - Returns True if the string starts with the specified prefix, optionally restricting the search to the specified start and end indices.

  34. strip(chars) - Returns a copy of the string with leading and trailing whitespace (or other characters specified by the chars parameter) removed.

  35. swapcase() - Returns a string where all uppercase characters are converted to lowercase and vice versa.

  36. title() - Returns a titlecased version of the string (i.e. the first character of each word is uppercase and the rest are lowercase).

  37. translate(table) - Returns a copy of the string where each character has been mapped through a translation table (e.g. replacing certain characters with other characters).

  38. upper() - Returns an uppercase version of the string.

  39. zfill(width) - Returns a copy of the string with zeros padded to the left to make it a specified width.

Example of All Methods in String:

# define a string
my_string = "Hello, world!"

# capitalize()
print(my_string.capitalize())  # "Hello, world!"

# casefold()
print(my_string.casefold())  # "hello, world!"

# center()
print(my_string.center(20, "*"))  # "***Hello, world!***"

# count()
print(my_string.count("o"))  # 2

# endswith()
print(my_string.endswith("!"))  # True

# find()
print(my_string.find("world"))  # 7

# index()
print(my_string.index("world"))  # 7

# isalnum()
print(my_string.isalnum())  # False

# isalpha()
print(my_string.isalpha())  # False

# isdecimal()
print(my_string.isdecimal())  # False

# isdigit()
print(my_string.isdigit())  # False

# isidentifier()
print(my_string.isidentifier())  # False

# islower()
print(my_string.islower())  # False

# isnumeric()
print(my_string.isnumeric())  # False

# isprintable()
print(my_string.isprintable())  # True

# isspace()
print(my_string.isspace())  # False

# istitle()
print(my_string.istitle())  # True

# isupper()
print(my_string.isupper())  # False

# join()
my_list = ["Hello", "world"]
print("-".join(my_list))  # "Hello-world"

# ljust()
print(my_string.ljust(20, "*"))  # "Hello, world!*******"

# lower()
print(my_string.lower())  # "hello, world!"

# lstrip()
print(my_string.lstrip("H"))  # "ello, world!"

# partition()
print(my_string.partition(","))  # ("Hello", ",", " world!")

# replace()
print(my_string.replace("world", "Python"))  # "Hello, Python!"

# rfind()
print(my_string.rfind("o"))  # 8

# rindex()
print(my_string.rindex("o"))  # 8

# rjust()
print(my_string.rjust(20, "*"))  # "*******Hello, world!"

# rpartition()
print(my_string.rpartition(","))  # ("Hello, world", ",", "")

# rsplit()
print(my_string.rsplit(","))  # ["Hello", " world!"]

# rstrip()
print(my_string.rstrip("!"))  # "Hello, world"

# split()
print(my_string.split(","))  # ["Hello", " world!"]

# splitlines()
multi_line_string = "Hello\nworld"
print(multi_line_string.splitlines())  # ["Hello", "world"]

# startswith()
print(my_string.startswith("Hello"))  # True

# strip()
print(my_string.strip("H!"))  # "ello, world"

# swapcase()
print(my_string.swapcase())  # "hELLO, WORLD!"

# title()
print(my_string.title())  # "Hello, World!"

# translate()
my_translation_table = my_string.maketrans("H", "J")
print(my_string.translate(my_translation_table))  # "Jello, world!"

# upper()
print(my_string.upper())  # "HELLO, WORLD!"

# zfill()
print(my_string.zfill(20))  # "0000Hello, world!"

Last updated