Strings

Strings are the simplest and easy to use in Python.

String pythons are immutable.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.

Accessing Strings:

In Python, Strings are stored as individual characters in a contiguous memory location.
The benefit of using String is that it can be accessed from both the directions in forward and backward.
Both forward as well as backward indexing are provided using Strings in Python.
Forward indexing starts with 0,1,2,3,....
Backward indexing starts with -1,-2,-3,-4,....

Simple program to retrieve String in reverse as well as normal form.

name="Gaurav"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
    print(name[i],"\t",name[n])
    i+=1

Output :

>>>>>>>>>>>>>>>>
G v
a a
u r
r u
a a
v G
>>>>>>>>>>>>>>

Strings Operators

There are basically 3 types of Operators supported by String:

1. Basic Operators

There are two types of basic operators in String. They are "+" and "*".

String Concatenation Operator : (+)

The concatenation operator (+) concatenate two Strings and forms a new String.

eg:

fullName = "Gaurav" + "Khanna"
print(fullName)

Output :

GauravKhanna

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

Replication Operator : (*)

Replication operator uses two parameter for operation. One is the integer value and the other one is the String.

The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.

Eg:

>>> 5*"Gaurav"

Output:

'GauravGauravGauravGauravGaurav'

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed cannot be of same type.

2. Membership Operators

There are two types of Membership operators:

1) in : "in" operator return true if a character or the entire substring is present in the specified string, otherwise false.

2) not in : "not in" operator return true if a character or entire substring does not exist in the specified string, otherwise false.

Eg:

>>> str1="notjustatester"
>>> str2='sssit'
>>> str3="seomount"
>>> str4='not'
>>> st5="it"
>>> str6="seo"

>>> str4 in str1
True

>>> str5 in str2
True

>>> str6 in str3
True

>>> str4 not in str1
False

>>> str1 not in str4
True

3. Relational Operators:

All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).

Eg:

>>> "GAURAV"=="GAURAV"
True

>>> "gaurav">='Gaurav'
True

>>> "Z"<>"z"
True

Explanation:

The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is 66,C is 67 and so on. The comparison between strings are done on the basis on ASCII value.