Built-in Methods for Strings in Python
Python provides a rich set of built-in methods for working with strings, which allow you to perform common tasks like capitalizing the first letter of a string, converting a string to lowercase, or splitting a string into a list of words. Here are a few examples of the built-in methods available in Python:
It’s necessary to be able to construct objects and call their methods in order to deal with objects in Python. In Python, a string is an example of a typical object type.
Strings are immutable, which means they cannot be changed, like those in other computer languages like Java. However, strings include built-in methods that you may use to change the contents of the string.
capitalize(): Returns a string with a capitalized first character, but not the rest capitalized.
lower(): Returns a copy of the string in lowercase.
Simply place a dot after the variable name, the name of the method, and any required parameters inside parentheses to call a method.
It’s essential to remember that these methods duplicate the original string rather than directly altering it.
To call a method in Python, you use the dot operator (.) after the variable name, followed by the method name and any parameters to pass to the method. For example, to convert a string to lowercase, you can use the lower() method like this:
x = “HELLO”
x = x.lower()
print(x) # Output: hello
In this example, the value of x is first set to “HELLO”.
Then, the lower() method is called on x, which returns a new string object that is a copy of the original with all letters in lowercase. Finally, the value of x is set to the result of x.lower(), so that x now points to the new lowercase string.
Summary
In this article, we have explored the basics of strings in Python and how they can be used in object-oriented programming. We have seen how to call built-in methods on strings, such as capitalize() and lower(), to manipulate the text data stored in strings. As you continue to work with strings in Python, you will discover many more built-in methods and techniques that can help you to write more efficient and effective code.