Built-in Methods for Strings -Part1

In this tutorial, I will discuss about the built-in methods for strings in python. We have seen all the methods available for strings with their short description while discussing about string datatype in python In this tutorial we will discuss about these built-in methods for strings in detail.

Built-in Methods for String

As we know, python provides special built-in methods for string objects. So let's see these methods and their use.

capitalize( )

If the first character of a string is not uppercase then capitalize() method returns a new string with the first character in uppercase and other characters in lowercase characters.

If the first character of a string is not a letter then it converts all other character to lowercase and returns the string.

Syntax of capitalize() method is :

string.capitalize( )

parameter : The capitalize() method does not take any parameter.

return : The capitalize() method returns a new string with first character in uppercase and other in lowercase.

Example 1 :

Str1 = "capiTAL this!!!"
print("string : ",Str1)
print("capitalize() method : ",Str1.capitalize())
string :  capiTAL this!!!
capitalize() method :  Capital this!!!

Example 2 :

Str2 = "123Try THis"
print("string : ", Str2)
print("capitalize() method : ",Str2.capitalize())
string :  123Try THis
capitalize() method :  123try this

casefold( )

This method converts all characters of a string into lowercase. If the string is already in lowercase then it simple returns the string as it is.

Syntax of casefold() method is :

string.casefold( )

parameter : The casefold() method does not take any parameter.

return : The casefold() method returns a new string with all characters in lowercase.

Examples :

str1 = "sTRInG"
print("string : ", str1)
print("casefold() method : ",str1.casefold())
str2 = "12happy"
print("string : ", str2)
print("casefold() method : ",str2.casefold())
string :  sTRInG
casefold() method :  string
string :  12happy
casefold() method :  12happy

center( )

The center() method is used to get a centered string. It also takes a character as a parameter and returns the centered string with padding.

Syntax of center() method :

string.center(width, fillchar)

parameter : The center() method takes total width in which the string is centered and a character which fills the empty space.

return : The center() method returns a new string with the string centered in the width and other spaces filled with character given as parameter.

Example :

print("hello".center(15,'*'))
print("hello".center(11))
*****hello*****
   hello   

count( )

The count() method returns the number of times a given character or substring is present in a string.

Syntax of count() method :

string.count(substring)

parameter : The count() method takes a character or a substring or a slice notation of the string as parameter.

return : The count() method returns the number of times the character or substring is present in the string.

Example :

str1 =  "string example.. this is string"
print("string : ",str1)
print("Number of t's in string : ",str1.count("t"))
print("Numbeer of 'str' substring in string : ",str1.count("str"))
string :  string example.. this is string
Number of t's in string :  3
Numbeer of 'str' substring in string :  2

encode( )

The encode() method returns encoded form of the string. There are many encodings supported by python like utf-8, utf-16, ascii etc. This method encodes the string into given encoding.

Syntax of encode() method :

string.encode(encoding)

parameter : The encode() method takes a encoding form supported by python as a parameter.

return : The encode() method returns the string in encoded format of given encoding.

Example :

print("123please help".encode('ascii'))
b'123please help'
print("help me".encode('utf-16'))
b'\xff\xfeh\x00e\x00l\x00p\x00 \x00m\x00e\x00'

endswith( )

The endswith() method is used to check whether the string ends with the given suffix substring. It returns False if the string does not end with that suffix.

Syntax of endswith() method :

string.endswith(suffix)

parameter : The endswith() method takes a suffix substring as a parameter, it also takes optional start index or stop index as parameter.

The start index is given to start the string checking from that position and stop index determines the end index for string comparision.

return : The endswith() method returns a bool variable (True or False). It returns True if the string ends with the given suffix in parameter and returns False if it does not end with that suffix.

Example :

Str_ex = "Check Ending"
print("string : ", Str_ex)
print("String endswith 'ing' ? ",Str_ex.endswith('ing'))
print("Part of string : ", Str_ex[0:5])
print("Part of string ends with 'eck' ? ", Str_ex.endswith('eck',0,5))
string :  Check Ending
String endswith 'ing' ?  True
Part of string :  Check
Part of string ends with 'eck' ?  True

expandtabs( )

The expandtabs() method returns the string with all the tab ( \t ) characters replaced by whitespace characters in multiples of tabsize parameter.

Syntax of expandtabs() method :

string.expandtabs(tabsize)

parameter : The expandtabs() method takes tabsize as a parameter. The method replaces the tab characters with white spaces in multiples of tabsize. By default the tabsize parameter takes value 8.

return : The expandtabs() method returns a new string with tab characters replaced by white space in multiples of tabsize parameter.

Example :

str1 = "azby\t123"
print("Original string : ", str1)
print("After expandtabs() : ",str1.expandtabs())
print("After expandtabs(2) : ", str1.expandtabs(2))
print("After expandtabs(4) : ", str1.expandtabs(4))
Original string :  azby 123
After expandtabs() :  azby    123
After expandtabs(2) :  azby  123
After expandtabs(4) :  azby    123

find( )

The find() method returns the index of a character or a substring given as parameter if it is found in the string. It returns -1 if the character or substring is not found.

Syntax of find() method :

string.find(substring)

parameter : The find() method takes a substring or character to find within the string as a parameter. it also takes a start or end index values as optional parameters. The start or end index values form a slice of the original string and the substring is then checked in that slice only.

return : The find() method returns index of first occurrence if the string contains the given substring, otherwise it returns -1.

Example :

str2 = "This is a dog."
print("Original string : ",str2)
print("str2.find('is') = ",str2.find('is'))
print("str2[5],str2[6] - ",str2[5],str2[6])
print("str2.find('dog',0,9) = ",str2.find('dog',0,9))
print("str2[0:9] = ",str2[0:9] )
Original string :  This is a dog.
str2.find('is') =  2
str2[5],str2[6] -  i s
str2.find('dog',0,9) =  -1
str2[0:9] =  This is a

format( )

We have seen the use of format() method while discussing Output in python. This method takes in variables or values or keyword arguments. The string has curly braces { } as placeholders where the arguments or values are used in the string.

Syntax of format() method :

string.format(arguments)

parameter : The format() method takes python variables, simple values/literals or keyword arguments as paramaters.

return : The format() method returns the formatted version of the string where placeholders are replaced with values passed as paramaters.

Example :

print("Hello, My name is {}, I am {} years old.".format('Rita',8)) #simple values/literals
a = 7
b = 'Rahul'
print("Hello, My name is {0}, I am {1} years old.".format(b,a)) #using python variables
print("Hello and {greet} to Learning {lang}.".format(lang='python', greet = 'welcome'))  # using keyword arguments
Hello, My name is Rita, I am 8 years old.
Hello, My name is Rahul, I am 7 years old.
Hello and welcome to Learning python.

format_map( )

We have seen the use of format() method while discussing Output in python. The format_map() method is another version of format() method.

This method takes a mapping or dictionary as parameter and then formats the string as per the values assigned in the dictionary.

The string has keys of the mapping or dictionary in curly braces { } as placeholders where the values from dictionary are used in the string.

Syntax of format_map() method :

string.format_map(mapping)

parameter : The format_map() method takes mapping or dictionary as parameter.

return : The format_map() method returns the formatted version of the string where placeholders with key are replaced with values from mapping or dictionary.

Example :

values = {'a' : 4, 'b' : 5}
values1 = {'a' : 3, 'b' : 1, 'c' : 7}
print("The coordinates of point1 are {a}, {b}".format_map(values))
print("The coordinates of point2 are {a}, {b}, {c}".format_map(values1))
The coordinates of point1 are 4, 5
The coordinates of point2 are 3, 1, 7

index( )

The index() method returns the index of a character or a substring given as parameter if it is found in the string. It raises ValueError if the character or substring is not found.

Syntax of index() method :

string.index(substring)

parameter : The index() method takes a substring or character to find within the string as a parameter. It also takes a start or end index values as optional parameters.
The start or end index values form a slice of the original string and the substring is then checked in that slice only.

return : The index() method returns index of first occurrence of the substring if the string contains the given substring, otherwise it raises ValueError.

Example :

str_in = "This is a string"
print("Original string : ",str_in)
print("str_in.find('str') = ",str_in.index('str'))
print("str_in[10],str_in[11],str_in[12] - ",str_in[10],str_in[11],str_in[12])
print("str_in.find('str',0,8) = ",str_in.index('str',0,8))
Original string :  This is a string
str_in.find('str') =  10
str_in[10],str_in[11],str_in[12] -  s t r

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
      3 print("str_in.find('str') = ",str_in.index('str'))
      4 print("str_in[10],str_in[11],str_in[12] - ",str_in[10],str_in[11],str_in[12])
----> 5 print("str_in.find('str',0,8) = ",str_in.index('str',0,8))

ValueError: substring not found

isalnum( )

The isalnum() method is used to check if the string contains only alphabetical and numerical characters. It returns True if the string is an alpha-numeric string, otherwise it returns False.

Syntax of isalnum() method :

string.isalnum( )

parameter : The isalnum() method does not take any parameters.

return : The isalnum() method returns True if the string is alphanumeric, otherwise it returns False.

Example :

print("This123is123alphanumeric : ","This123is123alphanumeric".isalnum())
print("This is alphanumeric : ","This is not alphanumeric".isalnum())
This123is123alphanumeric :  True
This is alphanumeric :  False

isalpha( )

The isalpha() method is used to check if the string contains only alphabetical characters. It returns True if the string is an alphabetical string, otherwise it returns False.

Syntax of isalpha() method :

string.isalpha( )

parameter : The isalpha() method does not take any parameters.

return : The isalpha() method returns True if the string is alphabetical, otherwise it returns False.

Example :

print("Thisisgreat : ","Thisisgreat".isalpha())
print("Grade2 : ","Grade2".isalpha())
Thisisgreat :  True
Grade2 :  False

isdecimal( )

The isdecimal() method is used to check if the string contains only decimal numbers. It returns True if the string has onlt decimal numbers, otherwise it returns False.

Syntax of isdecimal() method :

string.isdecimal( )

parameter : The isdecimal() method does not take any parameters.

return : The isdecimal() method returns True if the string contains only decimal numbers, otherwise it returns False.

Example :

print("123 : ","123".isdecimal())
print("\u00b2 : ", "\u00b2".isdecimal())
print("45.67 : ","45.67".isdecimal())
print("\u2163 : ","\u2163".isdecimal())
123 :  True
² :  False
45.67 :  False
Ⅳ :  False

isdigit( )

The isdigit() method is used to check if the string contains only digits. It returns True if the string has only digits, otherwise it returns False.

Syntax of isdigit() method :

string.isdigit( )

parameter : The isdigit() method does not take any parameters.

return : The isdigit() method returns True if the string contains only digits, otherwise it returns False.

Example :

print("123 : ","123".isdigit())
print("\u00b2 : ", "\u00b2".isdigit())
print("45.67 : ","45.67".isdigit())
print("\u2163 : ","\u2163".isdigit())
123 :  True
² :  True
45.67 :  False
Ⅳ :  False

isnumeric( )

The isnumeric() method is used to check if the string contains only numeric characters. It returns True if the string has only numeric characters, otherwise it returns False.

Syntax of isnumeric() method :

string.isnumeric( )

parameter : The isnumeric() method does not take any parameters.

return : The isnumeric() method returns True if the string contains only numeric characters, otherwise it returns False.

Example :

print("123 : ","123".isnumeric())
print("\u00b2 : ", "\u00b2".isnumeric())
print("45.67 : ","45.67".isnumeric())
print("\u2163 : ","\u2163".isnumeric())
123 :  True
² :  True
45.67 :  False
Ⅳ :  True

The methods isdecimal(), isdigit() and isnumeric() are used to check for numerical values in form of a string. But the main difference among them is that isdecimal() only accepts numbers, isdigit() will return True for numbers, superscript and subscript values and isnumeric() method returns True if the string is numbers, super/subscripts, fractions or roman numerals.

Note : The super/subscript and roman numerals are expressed in form of unicode encoded strings, this is a form of encoding supported by python.

Conclusion

In this tutorial, we have discussed about some of the built-in methods for strings in python with examples, we will continue to discuss about other built-in methods for strings in next tutorial.

If you have any questions please comment below, also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment