Strings and String Operations In Python

Document
Image description

Strings

The string is defined as any set of characters within either single quote or the double quotes.

        
    ex:
    s='Notes'
    s="Notes"        
        
    

HOW TO ACESS CHARCTERS OF THE STRING

There are two ways to access the characters in the string

  • By Indexing
  • By Slice Operator

Indexing

        
     s = "Notes"

    print(s[0])
    Output:N
            
    print(s[1])
    Output:o
            
    print(s[2])
    Output:t
            
    print(s[3])
    Output:e
            
    print(s[4])
     Output:s
                  
        
     

Slice Operators

Syntax: s[begin:end:step]

Begin: From where the we have to consider the slicing of the string
End: From where the slicing of the string will end at index -1
Step: It is the incremented value

    
ex: s='Notes'
    print(s[0:2:1])
    Output: No
    print(s[1:2])
    Output: o
    
 

Mathematical Operators in String

We can use Two types of mathematical Operators in String

  • '+' For concatenate
  • '*' For multiplication

Note : Both the arguments should be in string to concanecate and to multiply

len() Built in Function

We can use the len() function to find the number of characters present in the string

    
ex:
    s= "Notes"
    print(len(s))
    Output: 5       
    
  

Finding Substring

We can use four methods to find the string

  • For forward Direction -> index() ,find()
  • For backward Direction -> rindex() ,rfind()

find()

    
ex:
 s="notes"
 print(s.find("e"))
 Ourput:3      
    
  

Index()

The index method is same as find() the only difference is that it returns Value error if the required character o string is not

Replacing the String with another String

    
 ex:
 s1= "notes"
 s2 = print(s1.replace('notes','hello'))        
    

Splitting of the Strings

We can also split the strings by using split()

    
ex: s = 'python is a very good language'
s1 = s.split()
print(s1)
    

Joining of the Strings

    
ex:
s= ('My' ,'notes', 'are', 'very', 'good')
s1 = '-'.join(s)
print(s1)
    

Changing the case of the Strings

1. upper()===>To convert all characters to upper case
2. lower() ===>To convert all characters to lower case
3. swapcase()===>converts all lower case characters to upper case and all upper case characters to lower case
4. title() ===>To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
5. capitalize() ==>Only first character will be converted to upper case and all remaining characters can be converted to lower case

Follow on LinkedIn

Comments

Popular posts from this blog

Recursion In Python

Tkinter and Api

Sets in python