OneBite.Dev - Coding blog in a bite size

cut a string in python

Code snippet on how to cut a string in python

myString = "This is a sample string"

# use the split() method to return a list of substrings
# separated by the given delimiter
myStringList = myString.split(" ")

# print the newly created list
print(myStringList)

# access the desired substring
desiredSubstring = myStringList[3]

# print the desired substring
print(desiredSubstring)

This code sample cuts a string in python by using the split() method. The split() method returns a list of substrings that are each separated by a given delimiter. In this case, the delimeter is a space. The split() method is invoked on the original string which is stored in a variable called myString. Then the list that is returned from the split() method is stored in a variable called myStringList. We can then access the desired substring from the list by using an index. The index we use is 3 which returns the substring “sample” that is stored in a variable called desiredSubstring. We then print this substring to demonstrate that the code works properly.

python