String in Python 3 | Manipulating strings in Python

Preview
You must first complete Literals in Python before viewing this Lesson

What is a String in Python?

String is a sequence of characters within the pair of single quotes(‘) or double quotes (“).  

Example: “school”, “Rs100”, ‘$24.50’,’father-name’.

1. Creating a String Variable

To create a string variable, we need to put a string value into string variable using assignment operator

Syntax:

Stringvariable =”Value1”   OR Stringvariable=’Value1’

Stringvariable refers to name of variable defined by the programmer which can store a string value.

Value1 refers to sequence of characters within pair of doubel quotes(“) or single quotes(‘).

Example:

>>> Name=”lovejot”

>>> print(Name)
lovejot

Name is a string variable that contains string value “lovejot”.

>>> name1=’monika’

>>> print(name1)
monika

Name1 is a string variable that contains string value ‘monika’.

2. Accessing characters of a String

Each character of a string has an index associated with it.

Characters of a string are also indexed in two ways:

  1. FORWARD INDEXING AS 0,1,2,3,…
  2. BACKWARD INDEXING AS -1,-2,-3,…

Example we have a string word=”School”

Characters of above string are indexed as follows:

Index of first element of string is 0 (Forward Indexing) and -6 (Backward Indexing)

So we an access first element of above string as word[0] or word[-6]

Similarly we can access last element of above string as word[5] or word[-1].

Example

Python Code

Description

>>> word=’SCHOOL’ 
>>> word[0]
‘S’
First character of string is shown
>>> word[2]
‘H’
Third  character of list is shown
>>> word[-1]
‘L’
Last character of list is shown
>>> word[-3]
‘O’
Second character of list is shown

3. Slicing of Strings

We can view specific characters in a string by specifying the range of indexes within the pair of square brackets as:

string[First_index,Last_index,Gap].

string is the name of string variable whose characters we want to view.
First_index refers to the starting index.
Last_index refers to ending index.
Gap refers to the gap in indexes

Example

Python Code

Description

>>> word=’bestschool’ 
>>> word[0:3]
‘bes’
Characters at indexes 0,1,2 are shown.
>>> word[2:6]
‘stsc’
Characters at indexes 2,3,4,5 are shown.
>>> word[-6:-3]
‘sch’
Characters at indexes -6,-5,-4 are shown.
>>> word[0:7:2]
‘bssh’
Characters at indexes 0,2,4,6 are shown.
>>> word[-7:-2:2]
‘tco’
Characters at indexes -7,-5,-3 are shown.
>>> word[::-1]
‘loohcstseb’
String is reversed in the output.
>>> word[::-2]
‘locte’
String is reversed in the output with gap of -2. Values at indexes -1,-3,-5,-7,-9 are shown

 

4. Find number of characters in a string

Function len() of Python returns number of characters in a string value. The syntax of len() is

len(string)

string refers to sring value whose length we want to fine.

Example 1

Python Code

Description

>>> word=’bestschool’
>>> len(word)
10
Length of string variable word is returned as 10 because there are 10 characters in the string variable.

Example 2

Python Code

Description

>>> len(‘hello’)
5
Length of string value ‘hello’ is returned as 5 because there are 5 characters in the string value.

5. Membership operators on String

We can use ‘in’ and ‘not in’ operators with Strings

Example:

Python Code

Description

>>> word=”bestschool” 
>>> ‘e’ in word
True
Output is True because alphabet ‘e’ is contained in the string ‘bestschool’.
>>> ‘scl’ in word
False
Output is False ‘scl’ is not contained in the string variable word.
>>> ‘st’ not in word
False
Output is False because ‘st’ is contained in the string variable word.
>>> ‘BEST’ not in word
False
Output is False because ‘BEST’ is capital. Python distinguishes capital and small letters.

6.  Concatenation Operator on Strings

We can concatenate two string values by using concatenation operator (+).

Example 1:

Python Code

Description

>>> word1=’best’
>>> word2=’school’
 
>>> word1+word2
‘bestschool
String variables  word1 and word2 are joined together in the output

Example2:

Python Code

Description

>>> ‘1’+’2′
’12’
Strings ‘1’ and ‘2’ are joined together

Example3:

Python Code

Description

>> ‘1’+2
Traceback (most recent call last):
  File “<pyshell#28>”, line 1, in <module>
    ‘1’+2
TypeError: must be str, not int
String value ‘1’ can’t be joined with integer value 2

7. Replication Operator on Strings

We can use replication operator (*) to repeat a string value.

Example:

Python Code

Description

>>> ‘hello’*3
‘hellohellohello’
String value ‘hello’ is repeated three times in the output
>>> word1=’best’
>>> word1*2
‘bestbest’
Value of string variable word1=‘best’ is repeated twice.

8. Comparison of strings

We can compare string values by using relational operators of  Python.
Strings are compared character by character i.e. dictionary order.
Examples

Python Code

Description

>>> “K”==”K”
True
True is retured as both values are same
>>> ‘a’ !=’ abc’
True
True is returned because values are not same
>>> “XYZ”==’xyz’
False
False is returned because ‘XYZ” is in capital but ‘xyz’ is in small case.
>>> ‘xyz’ != “XYZ”
True
True is returned because ‘XYZ” is in capital but ‘xyz’ is in small case.

Python compare strings based on Unicode values of characters (ordinal value) .
Unicode values for commonly used characters are:

CharacterUnicode
‘0’ to ‘9’48 to 57
‘A’ to ‘Z’65 to90
‘a’ to ‘z’97to122

As per above table, upper case letters are considered smaller than the lower case letters..

Python Code

Description

>>> ‘a'<‘A’
False
Output is False because the Unicode value of  lower case alphabets is higher than upper case letters So ’a’ is not lesser  than ‘A’
>>> ‘ABC’>’AB’
True
Output is True as ‘ABC’ appears after ‘AB” in dictionary.
>>> ‘abc'<=’ABCD’
False
Output is False because ‘abc’ have higher Unicode values compared to’ABCD’
>>> ‘abcd’>’abcD’
True
Output is True because strings ‘abcd’ has higer unicode value than ‘abcD’.

9. Find Unicode of a Character

We can use function ord() to find unicode value of a character

Example:

Python Code

Description

>>> ord(‘a’)
97
Output is 97 because unicode of ‘a’ is 97.
>>> ord(‘A’)
65
Output is 65 because unicode of ‘A’ is 65.

10. Find character on the basis of Unicode

We can use chr() function of python to view a charater on the basis of unicode value.

Example:

Python Code

Description

>>> chr(65)
‘A’
Output is ‘A’ because unicode of ‘A’ is 65.
>>> chr(98)
‘b’
Output is ‘b’ because unicode of ‘b’ is 98.

11.Traversing  a String

Traversing is the technique of fetching each and every character of string at least once.
We can traverse individual characters of a string through their indexes. Using these indexes, we can traverse a string character by character.
We can use for() loop for traversing a string.
Example:

Python Code

Output

str=’hello’
for i in str:
    print(i)
h
e
l
l
o

Above code works in the following manner
Step 1. First character of string i.e. ‘h’ gets stored in str, It is shown
Step 2. Second character i.e. ‘e’ gets stored in str, It is shown
Step 3. Third character i.e. ‘l’ gets stored in str, It is shown
Step 4. Fourth character i.e. ‘l’ gets stored in str, It is shown
Step 5. Last character i.e. ‘o’ gets stored in str, It is shown

Lesson tags: operator on strings in python 3, string slicing in python 3, traversing a string in python3, using string in python 3
Back to: Python Programming Tutorial