In the previous tutorial, you learned how to use in-built math methods in your Python program with importing the math modules in Python. But, In this post, you will learn everything about python built-in string methods/functions.
What is string in Python?
In python, string is a sequence of characters and enclosed with quotation marks. If you want to know more about python strings click here.
Python provides many in-built methods/functions, which is work with python string datatype. And you can modify and manipulate strings by using built-in string methods/functions of these pythons.
We have provided a list below. Almost all python built-in string methods/functions are there:
Python String Methods/Functions
Method | Description |
---|---|
capitalize() | Converts the first character to upper case |
casefold() | Converts string into lower case |
center() | Returns a centered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier |
islower() | Returns True if all characters in the string are lower case |
isnumeric() | Returns True if all characters in the string are numeric |
isprintable() | Returns True if all characters in the string are printable |
isspace() | Returns True if all characters in the string are whitespaces |
istitle() | Returns True if the string follows the rules of a title |
isupper() | Returns True if all characters in the string are upper case |
join() | Joins the elements of an iterable to the end of the string |
ljust() | Returns a left justified version of the string |
lower() | Converts a string into lower case |
lstrip() | Returns a left trim version of the string |
maketrans() | Returns a translation table to be used in translations |
partition() | Returns a tuple where the string is parted into three parts |
replace() | Returns a string where a specified value is replaced with a specified value |
rfind() | Searches the string for a specified value and returns the last position of where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
rjust() | Returns a right justified version of the string |
rpartition() | Returns a tuple where the string is parted into three parts |
rsplit() | Splits the string at the specified separator, and returns a list |
rstrip() | Returns a right trim version of the string |
split() | Splits the string at the specified separator, and returns a list |
splitlines() | Splits the string at line breaks and returns a list |
startswith() | Returns true if the string starts with the specified value |
strip() | Returns a trimmed version of the string |
swapcase() | Swaps cases, lower case becomes upper case and vice versa |
title() | Converts the first character of each word to upper case |
translate() | Returns a translated string |
upper() | Converts a string into upper case |
zfill() | Fills the string with a specified number of 0 values at the beginning |
The built-in strings methods/functions of Python are given above in list. Understand those Python strings methods/functions with their definition and example.
And know how to use the built-in string of these python methods with string.
Python string method capitalize
The capitalize () method of Python converts the first character of the given string into upper case.
str = "hi, mac"
x = str.capitalize()
print (x)
#Ouput Hi, mac
casefold string method in python
The casefold() method returns a string where all the characters are lower case.
str = "Hi, Mac"
x = str.casefold()
print(x)
#output hi, mac
center method of string in python
Python center() method aligns string to the center by filling paddings left and right of the string. This method takes two parameters, first is a width and second is a fill char, which is optional.
str = "neveropen"
x = str.center(50)
print(x)
#output
# neveropen
str = "neveropen"
x = str.center(50, "O")
print(x)
#output
#OOOOOOOOOOOOOOOOOOOOOneveropenOOOOOOOOOOOOOOOOOOOOO
count method in python
The python count() method searches the substring in the given string and returns how many times the substring is present in it. It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.
str = "I love python, python is programming language"
x = str.count("python")
print(x)
#Ouput 2
encode method in python
In the python encode method, which is used to encode the give strings.
str = "python"
x = str.encode()
print(x)
#output b'python'
endswith method in python
The endswith() method returns True if a string ends with the given string. If not, it returns False.
text = "Python is easy to learn."
result = text.endswith('to learn.')
print(result)
# output True
expandtabs method in python
The expandtabs() method returns a copy of string with all tab characters ‘\t’ replaced with whitespace characters until the next multiple of tabsize parameter.
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
#xyz 12345 abc
find method in python
python find method, which is used to find first occurrence of substring. If it is not found in given string, it returns -1.
str = "let me test this string"
x = str.find("test")
print(x)
#output 7
format method in python
The format() method formats the specified string value(s) and inserts them inside the string’s placeholder.
The placeholder is defined using curly brackets: {}.
# default arguments
print("Hello {}, my fav no is {}.".format("Mac", 505))
# positional arguments
print("Hello {0}, my fav no is {1}.".format("Mac", 505))
# keyword arguments
print("Hello {name}, my fav no is {blc}.".format(name="Mac", blc=505))
# mixed arguments
print("Hello {0}, my fav no is {blc}.".format("Mac", blc=505))
#Output
#Hello Mac, my fav no is 505.
#Hello Mac, my fav no is 505.
#Hello Mac, my fav no is 505.
#Hello Mac, my fav no is 505.
index method in python
python index method finds the first occurrence of the given string. If it is not found in given string, it returns an error.
str = 'Python is good programming language.'
result = str.index('is good')
print("Substring 'is good':", result)
result = str.index('PHP')
print("Substring 'PHP':", result)
#Output
#Substring 'is good': 7
""" Traceback (most recent call last):
File "<stdin>", line 6, in <module>
result = str.index('PHP')
ValueError: substring not found """
isalnum method in python
The isalnum() method used to check all characters in the string are alphanumeric or not. If not, it returns False.
name = "Xyz353mt54j"
print(name.isalnum())
#output True
isalpha method in python
The isalnum() method used to check all characters in the string are alphabets or not. If not, it returns False.
name = "Python"
print(name.isalpha())
#True
isdecimal method in python
In python, the isdecimal () method is used to check if all the characters in a string are decimal characters. If not, it return false.
s = "12345"
print(s.isdecimal())
# contains alphabets
s = "42dk5"
print(s.isdecimal())
#Output
#True
#False
isdigit method in python
In python, the isdigit() method is used to check if all the characters in a string are digits. If not, it return false.
str = "123456"
print(str.isdigit())
# contains alphabets and spaces
str = "Py 45 tho 45"
print(str.isdigit())
#Output
#True
#False
isidentifier method in python
In Python the isidentifier () method is used to check whether a given string is a valid identifier. If not, it returns False.
str = 'Python'
print(str.isidentifier())
str = 'Py thon'
print(str.isidentifier())
#Output
#True
#False
isnumeric method in python
The isnumeric() method used to check all characters in the string is numeric characters. If not, it returns False.
str = '12345'
print(str.isnumeric())
#output True
isprintable method in python
The isprintable() methods used to check all characters in the string are printable or the string is empty. If it is not printable, it returns False.
str = 'Space is a printable in python'
print(str)
print(str.isprintable())
str = '\nNew Line is also printable'
print(str)
print(str.isprintable())
#output
#Space is a printable in python
#True
#New Line is also printable
#False
isspace method in python
The isspace() methods is used to check if the argument contains all whitespace characters. If it is not whitespace characters, it returns False.
str = ' \t'
print(str.isspace())
str = ' a '
print(str.isspace())
#Output
#True
#false
istitle method in python
The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.
str = "Welcome To Python World"
x = str.istitle()
print(x)
#output True
Python String Find()
The python find() method finds the lowest substring of the given string. If the substring found in a given string, it returns index of the substring. Otherwise, it returns -1.
string = 'Hello python learners, welcome to python course'
result = string.find('python')
print("Substring 'python':", result)
#output
#Substring 'python': 6
Python String rfind()
The python rfind() method finds the highest substring of the given string. If the substring found in a given string, it returns the index of the substring. Otherwise, it returns -1.
string = 'Hello python learners, welcome to python course'
result = string.rfind('python')
print("Substring 'python':", result)
#output
#Substring 'python': 34
Python strip method
Python strip() in-built method, which is used to remove all the leading and trailing spaces from a string (beginning and end (both sides) of a string).
str = ' xoxo love xoxo '
# Leading whitepsace are removed
print(str.strip())
print(str.strip(' xoxoe'))
#output
#xoxo love xoxo
#lov
Python lstrip() method
Python lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces.
str = ' this is first left string '
# Leading whitepsace are removed
print(str.lstrip())
#output
#this is first left string
Python rstrip() method
python rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces.
str = ' this is right side'
# Leading whitepsace are removed
print(str.rstrip())
#output
#this is right side
Python String replace()
The python replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring.
string = 'python is good programming language. Python is best programming language'
'''occurences of 'python' is replaced'''
print(string.replace('python', "The python"))
Python String join()
The Python String join() function returns a string that is the concatenation of the strings in iterable with string object as a delimiter.
s1 = ','.join(['a', 'b', 'c'])
print(s1)
#output
#a,b,c