String Methods

String Methods

To get offline help with string methods you can input in a Python Interpreter:


str.replace()

As it sounds like, the string replace method will replace one character or a set of characters with another.

The above code shows how to replace a character or many characters. However the replace method does not change the original variable until it is reassigned back to the variable.

There are at times when you would want to replace x amount of the next encounters, not all.

str.find()

The string method find(), will return the index of what is searched for. So the character 'd' is index 7 of the string.


If however what is searched for is not found. -1 is returned.

So if you try to use it in a slice without testing if it failed or not, you will be essentially inserting -1 in place of where the str.find() method goes.

str.capitalize(), str.title(), str.lower(), str.upper(), str.swapcase()

All of these methods effect the outcome of the capitalization of words inside of a string. The method capitalize() will capitalize the first character of the first word. The method title() will capitalize every first character of every word in the string. The method lower() will make all characters lowercase in the string. The method upper() will make all characters uppercase in the string. The method swapcase() will swap uppercase characters for lowercase characters and vice versa in the string.


str.split()

The method split() will chop the string into substrings into a list.


At which point you can splice and index the list.

You can also split by specific characters, which be default is whitepace. Here we split the string by commas instead.


str.join()

The method join() will join, for example, a list of all the indexes together into a string based on what you join them with.


There are numerous string methods available. Check >>>help(str) to view them in the python interpreter. There is also a very common str method that I gave its own section for due to it's complexity: the str.format(). This section can be found in string expressions and formatting.