“String methods” in Python.
Learn about some of Python’s built-in methods that can be used on strings.
In this article we will learn what are the different string methods in python.A string is a sequence of characters.A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's.
Strings in python are surrounded by either single quotation marks, or double quotation marks. For Example, ‘hello’ is the same as “hello”.
STRING METHODS.
In the above points we have seen what is a string?.Now let us see what are string methods.
Python has a set of built-in methods that you can use on strings which are assigned to do a particular task on data.
Here we shall learn about some of the more frequently used ones. Something important to note here is that all the string methods always return new values and do not change or manipulate the original string.
- Split( )
- Splits the string at the specified separator, and returns a list.
Example:
2. rsplit( )
The rsplit()
method splits a string into a list, starting from the right.
If no “max” is specified, this method will return the same as the split()
method.
SYNTAX:
string.rsplit (separator, maxsplit)
Example:
3. rstrip( )
The rstrip()
method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
SYNTAX:
string.rstrip(characters)
Example:
4. lstrip( )
The lstrip()
method removes any leading characters (space is the default leading character to remove)
SYNTAX:
string.lstrip(characters)
Example:
5. join( )
The join()
method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
SYNTAX:
string.join(iterable)
Example:
6. format( )
The format()
method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.
SYNTAX:
string.format(value1, value2…)
Example:
7. isnumeric( )
The isnumeric()
method returns True if all the characters are numeric (0-9), otherwise False.
SYNTAX:
string.isnumeric()
Example:
8. capitalize( )
The capitalize()
method returns a string where the first character is upper case, and the rest is lower case.
SYNTAX:
string.capitalize()
Example:
Conclusion
These were some of the useful built-in string methods in Python. There are others which are not mentioned in the article but are equally important. The Python documentation is an excellent resource if you are thinking to go deeper into the details.