CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

String Data Type in Python

Strings in Python
String Definition / What Is Strings in Python?

Python string is characters/numbers/special characters enclosed in quotes of any type - single quotation marks (' '), Double quotation marks ( " ") and triple quotation marks (" " "). An empty string is a string that has 0 characters (i.e. it is just a pair of quotation marks) Python string is immutable. you have used string in earlier chapters to store text type of data.

Every character of the string is given a special number that is called its index position. Consider the following string:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
my_string = "Hello World"
print(my_string)
print(type(my_string))

'''
Output:
Hello World
<class 'str'>
'''

#Index Positions
# H   e  l  l  o  W  o  r  l  d
# 0   1  2  3  4  5  6  7  8  9 (Forward)
#-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 (Backward)                         

By the above example, you can see that my_string is a variable of string type and all the characters of the string will have one unique index.

By now you must know that strings are a sequence of characters. where each character has a unique position - id/index. The index of a string begins from 0 and end on (length - 1) in the forward direction and -1,-2,-3....,-length in the backward direction. As in the example in the forward direction index are 0,1,2....,9 and in backward direction -1,-2,-3.....-10.

Accessing Individual elements of Python String

Since every elements has its Unique Index in Python we can access any element from string by just providing the Index in square brackets with string Name. See the following Example:
1
2
3
4
5
6
7
8
9
>>> my_string = "Hello World"                                      
>>> my_string[0]
'H'
>>> my_string[1]
'e'
>>> my_string[-1]
'd'
>>> my_string[-2]
'l'

Traversing A String -:

Traversing refers to iterating through the elements of a string, one character at a time. You know that individual characters of a string are accessible through the unique index of each character. Using the indexes you can traverse string character by character. We can traverse a string by using the for loop. You can write a loop like :
Example -:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
for i in "Hello World":                                            
     print(i)

'''
Output:
H
e
l
l
o

W
o
r
l
d
'''

String  Operators -:

You will be learning to work with various operators that can be used to manipulate strings in multiple ways. We will be talking about basic operators + and * membership operators in and not in and comparison operators (all relational operators) for strings.
  1.  Basic Operators
  2.  Membership Operators
  3.  Comparison Operators

(1) Basic Operators -: 

The two basic operators of the string are + and *. You have used these operators as arithmetic operators before for addition and multiplication respectively. But "+ operator" is used with string operands it performs "concatenation" rather than addition and "* operator" performs "replication" rather than multiplication.

Also before we proceed,  recall that strings and immutable i.e. and un-modifiable. Thus every time you perform something on a string that changes it Python will internally create a new string rather than modifying the old string in place.

a) Working Of Python * operators -:

The * operator, when used with numbers, (i.e.  When both your operands are numbers),  it performs multiplication and returns the product of the two number operands.

To use a * operator with string, you need to type of operands-:
(1) string
(2) number
It can be in the following forms:
number * string or string * number

Where string operands tell the String to be replicated and number operand tells the number of times, it is to be repeated. Python creates a new string that is a number of repeated addition of the string operator.
Example -:
1
2
3
4
5
6
>>> my_string = "Hello World"
>>> my_string * 3
'Hello WorldHello WorldHello World'
>>>
>>> 3 * my_string
'Hello WorldHello WorldHello World'                                

b) Working Of Python + Operators -:

This + operator has to either have both operands of the number types (for multiplication) or both should be of string type. It can not work with one operand string types and another as number type.
Example-:
1
2
3
4
5
6
>>> "Hello" + "World"
'HelloWorld'
>>> "Hello" + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str             
In the above example, you can see we can not add One String and One number.

(2) Membership Operators -:

There are two membership operators for string (in fact for all sequence types). These are in and not in. Let us learn about these operators in the context of strings.

in         -: Returns TRUE if a character or a substring exists in the given string; FALSE otherwise
not in  -: Returns TRUE if a character or a substring does not exist in the given string; FALSE otherwise

both membership operators (when used with string), require that both operands used with them are of string type i.e.
Example-:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> 'H' in 'Hello World'
True
>>> 'Y' in 'Hello World'
False


>>> 'H' not in 'Hello World'
False
>>> 'Y' not in 'Hello World'                                       
True

(3) Comparison Operators -:

Python standard comparison operators i.e. All relational operators (<,<=,>,>=, ==, !=)  apply to strings also. The comparisons using these operators are based on the Standard character by character comparison rules for Unicode (i.e. Dictionary order).

Equality and Non-Equality in strings are easier to determine because it goes for exact character matching for individual letters including the case (uppercase or lowercase) of the letter. 

But for another comparison like less than (<)  or greater than(>)  you should know the following piece of useful information. 
  • Python checks the Ordinal values while comparing String using (<, >, <=, >=).
  • You can find the ordinal value of any char by using ord(<char>) function. Find the characters and their ordinal values(ASCII values):
    Characters Ordinal Values
    ‘0’ to ‘9’ 48 to 57
    'A’ to ‘Z’ 65 to 90
    ‘a’ to ‘z’ 97 to 122
  • Ordinal values are compared character by character.
Example-:
1
2
3
4
5
6
7
'a'  <  'A'             False
'A'  >  'a'		True
'ABC' > 'AB'	        True
'abc' <=  'ABCD'	False                                      
'abc' < 'Acd'	        False
'abc' > 'Acd'	        True
'abcd'> 'A'	        True	

No comments:

Post a Comment