Skip to main content

String methods in python

Python String Methods

Python has very large set of in-built functions in strings which we can use directly without writing any extra code.

Note: We can store the result after applying methods into variables. There will be no change in the original string after applying these methods.

We will the methods step by step with examples.

1.) capitalize()
     It capitalizes the first letter of our string.
     
eg. 
str = "i am a word"
m=str.capitalize()

print(m)

Output:
I am a word

2.) casefold()
     It converts the characters of string into lowercase.

eg.
str = "SUN RISES IN EAST"
m=str.casefold()

print(m)

Output:
sun rises in east

3.) count()
      It returns the count of character that is passed.

eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
m=str.count("b") # returns cont of small b
n=str.count("B") # returns cont of capital B

print(m)
print(n)

Output:

11
2

You can also specify the starting and ending points in a string.It will count the elements within specified length.

eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"m=str.count("b",20,40) # returns cont of small between 20 and 40n=str.count("butter",30,50) # returns cont of capital butter between 30 and 50
print(m)
print(n)
Output:

2
1

4.) endswith()
     This method returns true if a string ends with a word or
     character specified in brackets.
eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
m=str.endswith("b") # returns cont of small b
n=str.endswith("butter") # returns cont of capital B

print(m)
print(n)

Output:

True
False

You can also specify the starting and ending points in a string.It will check the ending characters within specified length.
eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
m=str.endswith("u",20,40)

n=str.endswith("butter",40)


print(m)
print(n)

Output:

True
False

5.) find()
      Searches the string for a specified value and returns the index of  string where it was found. If the specified value occurs for more than one then it will return the index of string which it encounter first.

eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
m=str.find("b")

n=str.find("butter")


print(m)
print(n)

Output:

6
22

 You can also specify the starting and ending points in a string.It will find the string  within specified length.
eg.
str = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
m=str.find("b",30,50)

n=str.find("butter",40)


print(m)
print(n)

Output:

38
86

6.) index()
    It works in the same way as find works.Just you have to replace index with find.

7.) isalnum()
      It returns true if the characters in the string are alphanumeric(i.e it must be combination of alphabets and numbers, no other symbol is allowed) else return False.

eg.

string="Python123" # alphanumeric(combination of alphabets and numbers)
string1="Python 123" # Space is included
string2="Python" # only alphabets
string3="1234" # only numbers
string4="Python123$%^." # special characters included
b= string.isalnum()
b1= string1.isalnum()
b2= string2.isalnum()
b3= string3.isalnum()
b4= string4.isalnum()

print(b)
print(b1)
print(b2)
print(b3)
print(b4)

Output:
True
False
True
True

False

8.) isalpha()
      It returns true if all the characters in a string are alphabets else return false.
eg.

string="Python123" # alphanumeric(combination of alphabets and numbers)
string1="Python " # Space is included
string2="Python" # only alphabets
b= string.isalpha()
b1= string1.isalpha()
b2= string2.isalpha()

print(b)
print(b1)
print(b2)

Output:
False
False

True

9.) isdigit()
     It returns true if all the characters in a string are numbers.
eg.

string="Python123" # alphanumeric(combination of alphabets and numbers)
string1="Python" 

string2="123" 

b= string.isdigit()
b1= string1.isdigit()
b2= string2.isdigit()

print(b)
print(b1)
print(b2)


Output:
False
False

True

9.) isidentifier()
     It returns true if all the characters in a string are valid identifiers.

     A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

eg.

string="Python123_" # alphanumeric(combination of alphabets and numbers)
string1="_Python123" 

string2="123" 

string3="1python"

b= string.isidentifier()
b1= string1.isidentifier()
b2= string2.isidentifier()
b3= string3.isidentifier()

print(b)
print(b1)
print(b2)
print(b3)

Output:
True
True
False
False

10.) islower()
       It return true if all values in a string are in lowecase.

eg.

string="python123_" # alphanumeric(combination of alphabets and numbers)
string1="_Python123" # Space is included
string2="123"
string3="1python"b= string.islower()
b1= string1.islower()
b2= string2.islower()
b3= string3.islower()

print(b)
print(b1)
print(b2)
print(b3)

Output:
True
False
False

True

10.) isupper()
     It return true if all the characters in string are in uppercase.
eg.
string="PYTHON123_" # alphanumeric(combination of alphabets and numbers)
string1="_Python123" # Space is included
string2="123"
string3="1Python"b= string.isupper()
b1= string1.isupper()
b2= string2.isupper()
b3= string3.isupper()

print(b)
print(b1)
print(b2)
print(b3)

Output:
True
False
False

False

11.) isspace()
       It return true if all the characters in a string are spaces.
eg.

string=" "
string1="_ Python123"
string2=" g   "
b= string.isspace()
b1= string1.isspace()
b2= string2.isspace()

print(b)
print(b1)
print(b2)

Output:
True
FalseFalse

12.) lower()
       It converts all the characters in the string to lowercase.
eg.

string="PYTHON "
string1="_ Python123"

b= string.lower()
b1= string1.lower()

print(b)
print(b1)

Output:
python 
_ python123

 g   

13.) replace()
       It replaces the specified character or string with a particular character or word.
eg.

string = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
b= string.replace("butter","milk")

b1= string.replace(",","-")

print(b)
print(b1)

Output:
Betty bought a bit of milk, But the milk was so bitter, So she bought some better milk, To make the bitter milk better

Betty bought a bit of butter- But the butter was so bitter- So she bought some better butter- To make the bitter butter better

:We can also specify the number of occurrences upto which we want to replace the number.
eg.

string = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
b= string.replace("butter","milk",3)

b1= string.replace(",","-",2)

print(b)
print(b1)

Output:
Betty bought a bit of milk, But the milk was so bitter, So she bought some better milk, To make the bitter butter better

Betty bought a bit of butter- But the butter was so bitter- So she bought some better butter, To make the bitter butter better


14.) split()
       Split returns a list on the basis of separator you specify. By default it takes space as separator.
eg.

string = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
b= string.split()

b1=string.split(",")

print(b)
print(type(b))
print(b1)
print(type(b1))
       
Output:
['Betty', 'bought', 'a', 'bit', 'of', 'butter,', 'But', 'the', 'butter', 'was', 'so', 'bitter,', 'So', 'she', 'bought', 'some', 'better', 'butter,', 'To', 'make', 'the', 'bitter', 'butter', 'better']
<class 'list'>
['Betty bought a bit of butter', ' But the butter was so bitter', ' So she bought some better butter', ' To make the bitter butter better']

<class 'list'>

You can also specify the maxsplit in the given string.
eg.

string = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better"
b= string.split(" ",3)

b1=string.split(",",2)

print(b)
print(type(b))
print(b1)
print(type(b1))

Output:
['Betty', 'bought', 'a', 'bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better']
<class 'list'>
['Betty bought a bit of butter', ' But the butter was so bitter', ' So she bought some better butter, To make the bitter butter better']

<class 'list'>

You can also take input using split() method.
eg.

user_input=input("Enter string separated by spaces").split()

print("Your given input in list format is",user_input)

m,n=input("Enter two numbers seperated by space").split()

print("Two inputs are :",m,n)

Output:
Enter string separated by spaces 1 2 3 4 5 6 7
Your given input in list format is ['1', '2', '3', '4', '5', '6', '7']
Enter two numbers seperated by space 2 3

Two inputs are : 2 3

There are many more methods but these are the most important methods that we will be using.

14.) strip()
      An in-built function in python  which remove all trailing and leading spaces.
eg.
my_str="      strip is used  to remove spaces from start and end      "
print(my_str)
print("length of  original string",len(my_str))

my_str1=my_str.strip()
print(my_str1)
print("Length of string after removing spaces",len(my_str1))


















Comments

Popular posts from this blog

How to install python IDE ? IDLE and Pycharm

How to install Python IDE on Windows 10(Pycharm and IDLE)? Pycharm is the best Python IDE available.It comes with many in -built features. We will discuss its shortcuts in our next blogs.Pycharm is a cross-platform editor developed by jetbrains.   Installing Python Step 1) Visit the official website of python or click the below link              https://www.python.org/downloads/  .  Step 2) Click on Download Python               Step 3) After the download is complete ,open the exe file and click               on Install now  Step 4) After the successful installation it will show you a message         Setup was successful Step 5) Now go to your windows search bar and type "IDLE"              Press Enter and you will see that idle is opened Installing Pycharm St...

String Slicing in python

String Slicing Python  Slicing refers to extracting some words from a string. As in many other languages there are many different concepts for extracting a letters or words from a string ,in python we are having the concept of slicing. We can also the same things using looping, we will learn about it in our next tutorials. Indexing in Strings Before starting slicing, we need to understand the indexing in python. We have the concept of positive indexing  and  negative indexing.  Positive indexing starts from 0 to (length of string).It goes from forward to backward. Negative indexing starts from -1 to -(length of string + 1). It is illustrated in below example Below are some examples of how to use string slicing to extract characters from string. Accessing the characters in a string using positive index eg. string= "We are studying string slicing" s=string[ 0 ] # A single character will be printed present at index 0 w=string[ 4 ] # A...