Advertisement

Topic - 3


Python String

  • Till now, we have discussed numbers as the standard data types in Python. In this tutorial section, we will discuss the most popular data type in Python, i.e., string.
  • Python string is the collection of characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the feelings; internally, it stores manipulated characters as a combination of the 0's and 1's.
  • Each character is encoded in the ASCII or Unicode character. We can say that Python strings are also called the collection of Unicode characters.
  • A string in Python is a sequence of characters. It is enclosed in single quotes (') , double quotes (") and triple quotes(''')
  • Examples: 
        #Using single quotes  

str1 = 'Welcome Python'  

print(str1)  

#Using double quotes  

str2 = "Welcome Python"  

print(str2)  

#Using triple quotes  

str3 = '''''Triple quotes are generally used for  

    represent the multiline or 

    docstring'''   

print(str3)  

Output:

Welcome Python

Welcome Python

Triple quotes are generally used for

    represent the multiline or

    docstring

_______________________________________________________________________________

Strings indexing 

Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed as given in the below figure.


s

Example: 

str = "HELLO"  

print(str[0])  

print(str[1])  

print(str[2])  

print(str[3])  

print(str[4])  

# It returns the IndexError because 6th index doesn't exist  

print(str[6])  

Output:

H

E

L

L

O

IndexError: string index out of range

__________________________________________________________________________________________

Strings Positive Index position 

Examples: 

# Given String 

str = "International" 

# Start Oth index to end 

print(str[0:]) 

# Starts 1th index to 4th index 

print(str[1:5]) 

# Starts 2nd index to 3rd index 

print(str[2:4]) 

# Starts 0th to 2nd index 

print(str[:3]) 

#Starts 4th to 6th index 

print(str[4:7])


Output:

International

nter

te

Int

Rna



Strings Negative Index position 

str = 'International' 

print(str[-1]) 

print(str[-3]) 

print(str[-2:]) 

print(str[-4:-1]) 

print(str[-7:-2]) 

# Reversing the given string 

print(str[::-1]) 

print(str[-13])

Output:

l

n

al

ona

ation

lanoitanretnI

I

_________________________________________________________________

String Operators

Operator

Description

+

It is known as concatenation operator used to join the strings given either side of the operator.

*

It is known as repetition operator. It concatenates the multiple copies of the same string.

[]

It is known as slice operator. It is used to access the sub-strings of a particular string.

[:]

It is known as range slice operator. It is used to access the characters from the specified range.

in

It is known as membership operator. It returns if a particular sub-string is present in the specified string.

not in

It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.

r/R

It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as "C://python". To define any string as a raw string, the character r or R is followed by the string.

%

It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.    


     Examples of Operators :

str = "Hello"     

str1 = " world"    

print(str*3# prints HelloHelloHello    

print(str+str1)# prints Hello world     

print(str[4]) # prints o                

print(str[2:4]); # prints ll                    

print('w' in str) # prints false as w is not present in str    

print('wo' not in str1) # prints false as wo is present in str1.     

print(r'C://python37'# prints C://python37 as it is written    

print("The string str : %s"%(str)) # prints The string str : Hello   


Output:

HelloHelloHello

Hello world

o

ll

False

False

C://python37

The string str : Hello


Example: 

  # using triple quotes  

print('''''They said, "What's there?"''')  

# escaping single quotes  

print('They said, "What\'s going on?"')  

# escaping double quotes  

print("They said, \"What's going on?\"")  

Output:

They said, "What's there?"

They said, "What's going on?"

They said, "What's going on?"


_________________________________________________________________________________


Escape Sequence with Example


Sr.

Escape Sequence

Description

Example

1.

\newline

It ignores the new line.

print("Python1 \

Python2 \

Python3")

Output:

Python1 Python2 Python3

2.

\\

Backslash

print("\\")

Output:

\

3.

\'

Single Quotes

print('\'')

Output:

'

4.

\\''

Double Quotes

print("\"")

Output:

"

5.

\a

ASCII Bell

print("\a")

6.

\b

ASCII Backspace(BS)

print("Hello \b World")

Output:

Hello World

7.

\f

ASCII Formfeed

print("Hello \f World!")

Hello  World!

8.

\n

ASCII Linefeed

print("Hello \n World!")

Output:

Hello

 World!

9.

\r

ASCII Carriege Return(CR)

print("Hello \r World!")

Output:

World!

10.

\t

ASCII Horizontal Tab

print("Hello \t World!")

Output:

Hello    World!

11.

\v

ASCII Vertical Tab

print("Hello \v World!")

Output:

Hello

 World!

12.

\ooo

Character with octal value

print("\110\145\154\154\157")

Output:

Hello

13

\xHH

Character with hex value.

print("\x48\x65\x6c\x6c\x6f")

Output:

Hello


other Example: 

print("C:\\Users\\Poonam Sharma\\Python32\\Lib")  

2.      print("This is the \n multiline quotes")  

3.      print("This is \x44\x45\x46 representation")

output

C:\Users\Poonam Sharma\Python32\Lib

This is the

 multiline quotes

This is HEX representation

___________________________________________________________________________________

The format() method

The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument. Let's have a look at the given example:

  # Using Curly braces  

print("{} and {} both are the best friend".format("Ramesh","Mahesh"))  

#Positional Argument  

print("{1} and {0} best players ".format("Virat","Rohit"))  

#Keyword Argument  

print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))  

Output

Ramesh and Mahesh both are the best friend
Rohit and Virat best players 
James,Peter,Ricky 

__________________________________________________________________________________

  < <  Previous Topic-2 < <                                                                     > > Next Topic - 4 > >

__________________________________________________________________________________