Indexing
You can slice a string using smart indexing [] and : or ::
Example
temp_string = “abcdefghijk” # Create a string variable with value “abcdefghijk”
print(temp_string[1:]) # Slice from index 1 to the end and print that
print(temp_string[2:6]) # Slice from index 2 up to (but not including) index 6 and print that
print(temp_string[::-1]) # Reverse the string using slicing and print that
temp_string = "abcdefghijk"
print(temp_string[1:])
print(temp_string[2:6])
print(temp_string[::-1])
Result
bcdefghijk
cdef
kjihgfedcba
Concatenation
You can concatenate strings using the + operator
Example
first = “1234” # Create a string variable named first with value “1234”
second = “5678” # Create a string variable named second with value “5678”
print(first + second) # Concatenate the two strings and print that
first = "1234"
second = "5678"
print(first + second)
Result
12345678
Replace a letter or sub-string
You can use the .replace method to replace a word or letter in the string. The .replace method has 3 parameters (old value, new value, count)
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.replace(“!”, “$”)) # Replace all occurrences of “!” with “$” and print that
temp_string = "Hello World!"
print(temp_string.replace("!","$"))
Result
Hello World$
Or, you can replace a word
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.replace(“World!”, “Mike”)) # Replace the substring “World!” with “Mike” and print that
temp_string = "Hello World!"
print(temp_string.replace("World!","Mike"))
Result
Hello Mike
Also, you can remove a word by replacing it with nothing
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.replace(“World!”, “”)) # Replace the substring “World!” with an empty string and print that
temp_string = "Hello World!"
print(temp_string.replace("World!",""))
Result
Hello
Uppercase
You can use the .upper method to return a copy of the string in upper case
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.upper()) # Convert all characters in the string to uppercase and print that
temp_string = "Hello World!"
print(temp_string.upper())
Result
HELLO WORLD!
Lowercase
You can use the .lower method to return a copy of the string in upper case
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.upper()) # Convert all characters in the string to lowercase and print that
temp_string = "Hello World!"
print(temp_string.lower())
Result
hello world!
Split
You can use the .split method to split the string. The split method has 2 parameters (separator, max_split) and the result is a list
Example
temp_string = “Hello World!” # Create a string variable with value “Hello World!”
print(temp_string.split(” “)) # Split the string into a list using space as the separator and print that
temp_string = "Hello World!"
print(temp_string.split(" "))
Result
['Hello', 'World!']
Join
You can use the .join method to convert a list of strings into one single string
Example
temp_items = [“Hello”, “World”, “1”] # Create a list of strings
print(“,”.join(temp_items)) # Join all elements of the list into a single string, separated by “,” and print that
temp_items = ["Hello","World","1"]
print(",".join(temp_items))
Result
Hello,World,1
Find
You can use .find to return the index of the first occurrence if found; Otherwise, it returns -1
Example
temp_string = “0123456789” # Create a string variable with value “0123456789”
print(temp_string.find(“34”)) # Find the starting index of the substring “34” and print that
temp_string = "0123456789"
print(temp_string.find("34"))
Result
3
Count
You can use .count to return the number of occurrences if found; Otherwise, it returns 0
Example
temp_string = “1122334455” # Create a string variable with value “1122334455”
print(temp_string.count(“1”)) # Count how many times the substring “1” appears in the string and print that
temp_string = "1122334455"
print(temp_string.count("1"))
Result
2
String Class
When you assign a string to a variable, it will create an str object, the str open includes different methods like __str__ that returns the defined string
Example
temp_var = “test” # Create a variable named temp_var and assign it the string “test”
print(type(temp_var)) # Print the type of temp_var
temp_var = "test"
print(type(temp_var))
Result
<class 'str'>
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Custom Example
class string(): # Define a class named string
def __init__(self, var): # Constructor method, called when creating a new object
self.var = var # Store the argument var in the instance variable self.var
def __str__(self): # Define the string representation for printing
return “{} __str__”.format(self.var) # Return the string with “__str__” appended
def __eq__(self, other): # Define equality comparison for string objects
if isinstance(other, string): # Check if other is also an instance of string
return (self.var == other.var) # Compare the stored values
return False # If other is not a string object, return False
print(string(“test”) == string(“test”)) # Compare two string objects and print that
class string():
def __init__(self, var):
self.var = var
def __str__(self):
return "{} __str__".format(self.var)
def __eq__(self, other):
if isinstance(other, string):
return (self.var == other.var)
return False
print(string("test") == string("test"))
Result
True