Common String Methods

String methods are built-in Python functions that perform specific operations on strings. They’re used to perform tasks such as changing the case of a string, splitting a string into a list, and replacing parts of a string with other strings. In this guide, you will learn about some of the most commonly used string methods.

len() method

The len() method returns the length of a string. This includes spaces and punctuations as well.

1string = "Hello, World!"
2print(len(string))

In this code, the output will be 13, as there are 13 characters (including punctuation and spaces) in the string “Hello, World!”.

lower() and upper() methods

The lower() and upper() methods are used to change the case of all characters in a string. The lower() method converts all characters to lowercase, while the upper() method converts all characters to uppercase.

1string = "Hello, World!"
2print(string.lower())
3print(string.upper())

The output will be hello, world! and HELLO, WORLD! respectively.

str() method

The str() method converts a non-string data type to a string.

1integer = 123
2print(str(integer))

In this code, the output will be 123, but as a string, not an integer.

replace() method

The replace(old, new) method replaces all occurrences of the old string with the new string.

1string = "Hello, Codebay"
2new_string = string.replace("Codebay", "World")
3print(new_string)

The output of the above code will be Hello, World.

split() method

The split() method splits a string into a list where each word is a list item.

1string = "Hello, World!"
2print(string.split())

The output will be ['Hello,', 'World!'], a list of individual words in the original string.

Note

Remember, strings are immutable in Python. Therefore, all of these methods return a new string and do not modify the original.

These are only some of many string methods in Python. Others include strip(), join(), count(), find(), isdigit(), and many more. Familiarity with these methods is key to manipulating and working with strings in Python efficiently.