top of page

Python String Methods And Its Uses

In this blog, we will learn all python String Methods and how to implement these methods with python coding parts.


Now lets we will start with all-important python string topics :


1 - count()


Count appearance of the word in the strings


>>> string = "this is an apple, apple is delicious food"

>>> c = string.count("apple")

>>> print(c)


Output: 2


Search specified value in the given range


It is also used to search specified value within the given range:


>>> c = string.count("apple", 10, 20)



2 - capitalize()


Use to change the first letter of string lowercase to upper case.


>>> c = string.capitalize()


Output:


This is an apple, apple is delicious food.



3 - center()


Use to centralized the specified string.


>>> str = "codersarts"


>>> a = str.center(10)


>>> print(a)


It prints a string in the middle of 18 space which is taken up.


Output :


----codersarts----


Fill this space with another character


>> a = str.center(10, 's')


>>> print(a)


Output :


sssscodersartssss



4 - find()


It is the same as index(), but here little difference between find() and index() methods. find() return -1 if the value is not found and index() return exception if the specified value is not found.


>>> a = str.find("o")


It returns the index value of the first "o" in the strings.


>>> print(a)


Output :


1


Find specified string into the given range


>>> a = str.find("r", 5, 8)


Output :


7



5 - format



It used to format the value and insert it into the specified string place holder.


>>> print("Hi, this is {} and located in {}".format("codersarts", "India") )


or


>>> print("Hi, this is {name} and located in {location}".format(name = "codersarts", location = "India") )


or


>>> print("Hi, this is {0} and located in {1}".format("codersarts", "India") )



Formatting Types


Inside place holder, you can use different types of formating


:<integer value - Use for left-align the value as per given inter value

:>interger value - Use for right align the value as per given inter value

:for :2f - Use to fixpoint number decimal


>>> print("the price of the notebook is {:2f}, which is good ".format(49.505) )


Output is :


the price of the notebook is 49.50, which is good


or


>>> print("the price of the notebook is {:<8}, which is good ".format(49.505) )


the price of the notebook is 49.50 , which is good



Thanks for reading this blog if anything is missing then comments in below or need help in any types project then contact us at here

Comments


bottom of page