Python String Methods. A summary of the most commonly used... | by Robert Alterman | Towards Data Science

In Python, data in text form is known as a string. To designate data as a string, the text must be surrounded by single (‘ ’) or double (“ ”) quotes. Names, locations, objects, sentences, even numbers can be strings, as long as they are surrounded by quotes. Once you have a string, you are able to manipulate that string using what’s known as a ‘method.’ To use a method, you simply write the string followed by .[method](). For example, to run the upper() method on the string ‘pizza’, you would just write ‘pizza’.upper(); if ‘pizza’ were set to a variable, you would do that variable.upper(). Some methods accept what are known as ‘arguments,’ which go in the parenthesis and further define what the method will do. The Python language has a lot of built-in methods, like upper(), that allow you to easily alter strings.
These methods all perform simple manipulations on strings and take no arguments.
The upper() method converts every letter in a string to uppercase:
Syntax: string.upper()'pizza'.upper() --> 'PIZZA'
The lower() method converts every letter in a string to lowercase:
Syntax: string.lower()'PIZZA'.lower() --> 'pizza'
The title() method capitalizes the first letter of every word in a string, like a title:
Syntax: string.title()'i love to eat pizza'.title() --> 'I Love To Eat Pizza'
The capitalize() method is similar to the title() method; however, only the first letter of the first word in a string gets capitalized, like a sentence:
Syntax: string.capitalize()'i love to eat pizza'.capitalize() --> 'I love to eat pizza'
Remember, all of these examples can also be written using variables:
food = 'pizza'food.upper() --> 'PIZZA'
The split() method converts a string into a list. The method can take two optional arguments. The first argument is the separator, which tells the code how you want the string to be split. By default, the string is split at any whitespace, but if you choose you can decide on any character(s) by which to split the string. The second argument specifies the maximum number of splits to be done. By default, this number is set to -1 which is all occurrences.
Syntax: string.split(separator, maxsplit)'I like to eat pizza'.split() --> ['I', 'like', 'to', 'eat', 'pizza']'I like to eat pizza'.split('e') -->['I lik', ' to ', 'at pizza']'I like to eat pizza'.split('e', 1) -->['I lik', ' to eat pizza']
Similar to split(), the partition() method splits a string by a specified character(s). However, with this method, the string is split into a tuple consisting of three items: everything before the match, the match itself, and everything after the match. By using partition() instead of split() you are able to keep the character(s) by which you split the string. This method takes one required argument — the separator, which tells the code how you want the string to be split. If the separator is not found in the string, a tuple with three items is still returned; however, it consists of the whole string, an empty string, and another empty string.
Syntax: string.partition(value)'I like to eat pizza'.partition(' to ') --> ('I like', ' to ', 'eat pizza')'I like to eat pizza'.partition(' drink ')--> ('I like to eat pizza', '', '')
The join() method is used to join all of the items in an iterable (list, dictionary, tuple, set, or even another string) to a string. The method takes one required argument, the iterable. The string that is used before the method is applied is inputted in between each item in the iterable. Oftentimes, a string consisting of solely a space (‘ ’ or “ ”) is used with the join() method to create spaces between words in an iterable.
Syntax: string.join(iterable)' '.join(['I', 'like', 'to', 'eat', 'pizza']) --> 'I like to eat pizza''x'.join(['I', 'like', 'to', 'eat', 'pizza'])--> 'Ixlikextoxeatxpizza''yummy'.join({'food':'Pizza', 'topping': 'pepperoni'})--> 'foodyummytopping'
The replace() method allows you to replace a specified value of a string with another value. This method takes three arguments, the first two of which are required. The first argument is the value of the string that you wish to replace and the second argument is the value that will be taking its spot. The third argument is an integer specifying the number of occurrences of the value you want to replace — the default is all occurrences.
Syntax: string.replace(oldvalue, newvalue, count)'I like to eat pizza'.replace('pizza', 'burgers')--> 'I like to eat burgers''I really really like to eat pizza'.replace('really', 'kind of', 1)--> 'I kind of really like to eat pizza'
The strip() method removes any characters of your choosing from the beginning or end of a string. The method can take one optional argument. By default, any leading or trailing whitespaces are removed from the string, but you can choose to instead remove any characters of your choice if you include them in a string as an argument.
Syntax: string.strip(characters)'   pizza   '.strip() --> 'pizza''..rjq,,pizza.rq,j.r'.strip('rjq.,') --> 'pizza'
The startswith() method returns True if the string starts with the specified value and False otherwise. The endswith() method works the same way but with the end of a string. These methods take three arguments, the first of which is required while the latter two are optional. The first argument is the value you are looking to see if the string starts/ends with. The second argument is an integer value specifying which index you want to start the search and the third argument is the value of the index where you want to end the search.
Syntax: string.[starts/ends]with(value, start, end)'I like to eat pizza'.startswith('I like') --> True'I like to eat pizza'.endswith('drink pizza') --> False'I like to eat pizza'.startswith('to', 7, 18) --> True'I like to eat pizza'.endswith('eat', 7, 18) --> False
The count() method tells you how many times a specified value appears in a string. This method takes three arguments, the first of which is required. The first argument is the value that you are searching for in the string. The second and third arguments are the positions where you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string.
Syntax: string.count(value, start, end)'I really really like to eat pizza'.count('really') --> 2'I really really like to eat pizza'.count('really', 8, 20) --> 1
The find() and index() methods are nearly exactly the same in that they both return the index of the first occurrence of a specified value (the index of the first character of the specified value if the given value is multiple characters). The only difference between the two is that the find() method will return -1 if the value is not found in the string, while the index() method will result in an error if the value does not occur. Both methods take three arguments, the first of which is required. Like the count() method, the first argument is the value that you are searching for in the string, and the second and third arguments are the positions in which you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string.
Syntax: string.[find/index](value, start, end)'I really really like to eat pizza'.find('really') --> 2'I really really like to eat pizza'.index('really') --> 2'I really really like to eat pizza'.find('really', 8, 20) --> 9'I really really like to eat pizza'.index('really', 8, 20) --> 9'I really really like to eat pizza'.find('hamburger') --> -1'I really really like to eat pizza'.index('hamburger') --> ERROR
And there you have it. With these aforementioned methods you should be set to perform most of the operations you will need on Python strings. To see all of the available string methods, make sure to check out the w3schools list.
Happy coding and be sure to check out my blog on Python list methods below!