Strings in Python

 STRINGS

  • Strings are sequence of characters enclosed within single quotes ( '   ' ) or double quotes ("   ").
  • We can display strings with print function.
  For example:  Input:  mystr="Hello World!" 
                   print(mystr) 
                                         OR   
                              Input: print("Hello World!")                
                         Output:   Hello World!

  • In Python we can write multiline strings using triple quotes  ( ' ' '      ' ' '  ).
For exampleInput:   mystr = '''Hello !
              Welcome to world of programming!
              Are you ready    ''' 
                                      print(mystr)
                         Output: Hello !
      Welcome to world of programming!
      Are you ready 

There are two operations on Strings :

1) Indexing :  In Python we use Indexing on strings to access individual characters in String.
Example :  Input : mystr = "Hello"
                                    print(mystr[0])
                   Output :  H

• We can access last character in string by negative indexing as follows :
                        print(mystr[-1])
        Output :  o


2) Slicing :  Slicing returns a sub string from a given string by slicing it from start to end.
It is used to return range of characters.

Slicing has three parameters as follows:
• start : Starting index where the slicing of object stars.
stop : Ending index where the slicing of object stops. 
step : Step is optional argument which can pass a character depending upon step provided.

Syntax : string_name[start:stop:stop]

Examples : 
1) To get character from specific index to end.
     In : mystr = "Hello"
     mystr[1:]
   Out : 'ello'

2) To get character from specific index to specific end. (Note: Python returns characters until stop index not stop index)
     In : mystr[1:4]
  Out : 'ell'   (Here 4th index position in excluded.)

3) To get range of characters at step size of 2.
      In : mystr[0::2]
    Out : 'Hlo' ( Here step size of 2 is taken so it will                              exlude one character between two                                characters and print string as a whole                          because we have not mention stop index.                       for Slicing.)

4) We can also reverse a string using Slicing as follows:
     In: mystr[::-1]
 Out :  'olleH'
  

Some commonly used string functions :



Examples of above methods are as follows :






Comments

Popular posts from this blog

Introduction to Python Programming

Lists in Python

Variables in Python.