Python String

String literals or String in python can be created using single(‘’) or double(“”) or Triple inverted quotes(‘’’ or “””).When we use triple quotes, strings can span several lines without using the escape character.

Example

str1 = 'Computer Applications'                                          # string with single quotes
str2 = "Applications of computer"                                  # string with double quotes
str3 = """Official website  of                                            # string with triple quotes Python language

is:  http://www.python.org/”“”

When a string is defined inside Python it automatically generates an index for its each and every character. Using these indexes, individual items of the string can be accessed.

 

Python indexes the characters in a string from left to right and from the right end to left.  Left to right,  the first character of a string has the index 0  ( Zero ) right end to left, the first character of a string is –size  Let us see a string called ‘COMPUTER’ with its index positions:

In the above example, we have accessed string elements using an index from left to right and right to left.

Slicing in String

A substring of a string is called a slice. Subsets of strings can be taken using the slice operator ([m:n:step]) The operator [m:n] returns the part of the string from the mth position and up to but not including position n, i.e., n – 1.  The step value is by default +1 ie it moves from left-hand side to right-hand side.

Example
>>>str1 =”Python in Schools Now”
>>>print(str1[2:6] # print character from position 2 to 5
>>>print(str1[7:15] # print character from 5 to 14 position
>>>print(str1[:10] # print all the characters from position 0 to 9. When m is not defined it start with zero index
>>>print(str1[3:] # print all the characters from 3rd position to last index, when N is not defined it
print up to the end of the string
>>>print(str1[::2] #print all the character from 0 index to last index skipping every second character

Python String and Looping

Python string can be used with for loop also as for loop takes an iterative item for processing.  A simple example to display each element of a string in a separate row.

Example program

str1 = ‘Python’
for x in str1
       print(x)

The output of the above program is as follows

P
y
t
h
o
n

Concatenation and replication

String in Python can be joined using the (+) operator. For example, if we have two variables first =”rakesh” and second=”kumar” then we can join both of them using the + operator

first ="rakesh"
second ="kumar"
fullname = first + second
print(fullname)

when multiplication symbol(*) is used with string then it multiply the string.

 

symbol ="rakesh"
ouput = symbol*4
print(output)

containership operator in Python String

The membership operators are used to test whether a value is found in a sequence (string, list, tuple,  set, and dictionary). There are two types of membership operators.

containership operator

IN operator is known as a containership operator and it is also supported by the string in Python. In order to explain the working of IN operator, a vowel finder program in a string is the best solution. You can find out total number of vowels in a String

Comparing String

Strings can be compared with the standard operators relational or comparison operators like ==, !=, <,>, <= and >=. These comparisons use the standard character-by-character comparison rules for ASCII or  Unicode. The comparison operator returns a Boolean result True or False.

comparing string in python

Sample Question :  Write a program in Python to Enter a word and check with the word “PYTHON” whether the word comes after “PYTHON” or before “PYTHON”

word = input("Enter any word : ")  
if word < "PYTHON": print ("Your word, " + word + ", comes before PYTHON.") elif word > "PYTHON":
       print ("Your word, " + word + ", comes after PYTHON.")
else:
       print ("Yes, we have no choice!")

String functions and Methods

A string object has a number of functions and methods. The string functions uses a number of parameters. The dot operator (.) is used along with the string to access string functions except len() function.

Function

Description

len()This method returns the length of the string.

str1 = “Chennai Express“

print(len(str1)) 

# returns: 15

strip() 

lstrip()

rstrip()

The strip() method removes any whitespace from the beginning or the end.

a = ”  Hello World  ” 

# string has leading and trailing spaces  print(a.strip() + ‘friends’) 

# returns: hello worldfriends

Note: You can try lstrip() and rstrip() functions to strip leading and trailing spaces

upper()

lower()

The upper() method converts all the characters of the string into uppercase string.

a = “Hello World“

print (a.upper()) 

# returns: HELLO WORLD

Note: You can try lower() method to coverts all the characters into lowercase.

replace()This method returns a copy of the string with all the occurrences of old substring replaced by  new substring.

a = “Hello World“

print(a.replace(“H”, “J”))  # returns: Jello World

>>> print(a)  # returns: Hello World

Note: The string is immutable so J replaced H for printing in that line only physically string is  not changed.

split()This method returns a list of all the words in the string using a separator.

str1 = “Python In CBSE Schools”

print (str1.split(‘ ‘)) 

# returns: [‘Python’, ‘In’, ‘CBSE’, ‘Schools’]

print (str1.split(‘ ‘, 1)) 

# returns: [‘Python’, ‘In CBSE Schools’]

capitalize()This method returns a copy of the string with only its first character capitalized.

str1 = “python in CBSE schools“

print (str1.capitalize()) 

# returns: Python in cbse schools

istitle()This method checks whether each character in a string start with an upper case letter or not.

str1 = “Python In CBSE Schools“

print (str1.istitle()) 

# returns: False

str1 = “Python In Cbse Schools“

print (str1.istitle()) 

# returns: True

isspace()This method checks whether the string consists of whitespace or not.

str1 = ”  ”  # only spaces

print (str1.isspace()) 

# returns: True

str2 = “001-Delhi STD” 

# mix characters

print (str2.isspace()) 

# returns: False

isdigit()

 

This method return True if all the chars in the string are digits otherwise return False

syntax

str.isdigit()

Example

>>>str = “123343”

>>>print(str.isdigit()

>>>True

isalpha()

 

This method return True if all the chars in the string are alpahbets(a-z or A-Z) otherwise return False

syntax

str.isalpha()

Example

>>>str = “PythonClub3”

>>>print(str.isalpha()

>>>False

Count()This method returns the number of occurrences of a substring inside a string.

str1 = “This is Python string class and this is interesting”  sub = “is”

print (“This string {} occurs: {}”.format(sub, str1.count(sub))) 

# returns: This string is occurs: 4

These are few functions and methods that we thought you must learn in the string. Python String Assignment will help you to check your string skills, for more information on string methods, you can check python documentation.

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.