Unit 1 - Strings

 CBSE Revision Notes

Class-11 Informatics Practices (New Syllabus)
Unit 1: Programming and Computational Thinking (PCT-1)


Strings

Strings: Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example

Str1=’Hello world’

Str2=”I Love Programming”

Comparison of two strings:

str1=input("Enter first string")

str2=input("Enter second string")

if str1 == str2:

print(“Strings are Equal”)

else:

print("Strings are not Equal")

Concatenation of strings: This can be done by simple “+” operator.

str1=input("Enter ist string: ")

str2=input("Enter second string: ")

print("Strings after concatenation", str1 + str2)

Substring:

s = "abcdefghijklmnopqrs"

# Loop over some indexes.

for n in range(2, 4):

# Print slices.

print(n, s[n])

print(n, s[n:n + 2])

print(n, s[n:n + 3])

print(n, s[n:n + 4:2])

print(n, s[n:n + 6:2])

Result of this program:
2 c
2 cd
2 cde
2 ce
2 ceg
3 d
3 de
3 def
3 df
3 dfh

1. Python String with String Functions and String Operators

In this Python String tutorial, we will discuss about Python string with string functions and Operators. We will learn how to declare and slice a string in python, and also look at the Python String functions and operations you can apply and perform on it. As we saw earlier, you don’t need to mention the data type when declaring a string. Well, let’s begin the tutorial on Python String with Python String Operations and Functions.

Python Strings and Python String Operations and Functions

2. Introduction to Python String

A Python string is a sequence of characters. There is a built-in class ‘str’ for handling Python string. You can prove this with the type() function.

>>> type('Dogs are love') <class 'str'>

  1. >>> type('Dogs are love')
  2. <class 'str'>
>>> type('Dogs are love')
<class 'str'>

Python doesn’t have the char data-type like C++ or Java does.

3. Declaring a Python String

You can declare a string using either single quotes or double quotes.

>>> a='Dogs are love' >>> print(a)

  1. >>> a='Dogs are love'
  2. >>> print(a)
>>> a='Dogs are love'
>>> print(a)

Dogs are love

>>> a="Dogs are love" >>> print(a)

  1. >>> a="Dogs are love"
  2. >>> print(a)
>>> a="Dogs are love"
>>> print(a)

Dogs are love

However, you cannot use a single quote to begin a string and a double quote to end it, and vice-versa.

>>> a='Dogs are love">>> a='Dogs are love"

SyntaxError: EOL while scanning string literal

4. Using quotes inside a Python string

Since we delimit strings using quotes, there are some things you need to take care of when using them inside a string.

>>> a="Dogs are "love"">>> a="Dogs are "love""

SyntaxError: invalid syntax

If you need to use double quotes inside a string, delimit the string with single quotes.

>>> a='Dogs are "love"' >>> print(a)

  1. >>> a='Dogs are "love"'
  2. >>> print(a)
>>> a='Dogs are "love"'
>>> print(a)

Dogs are “love”

And if you need to use single quotes inside a string, delimit it with double quotes.

>>> a="Dogs are 'love'" >>> print(a)

  1. >>> a="Dogs are 'love'"
  2. >>> print(a)
>>> a="Dogs are 'love'"
>>> print(a)

Dogs are ‘love’

You can use as many quotes as you want, then.

>>> a="'Dogs' 'are' 'love'" >>> print(a)

  1. >>> a="'Dogs' 'are' 'love'"
  2. >>> print(a)
>>> a="'Dogs' 'are' 'love'"
>>> print(a)

‘Dogs’ ‘are’ ‘love’

5. Spanning a string across lines

When you want to span a string across multiple lines, you can use triple quotes.

>>> a="""Hello Welcome""" >>> print(a)

  1. >>> a="""Hello
  2. Welcome"""
  3. >>> print(a)
>>> a="""Hello
Welcome"""
>>> print(a)

Hello

Welcome

It preserves newlines too, unlike using a backward slash for the same.

>>> a="Hello\ Welcome" >>> print(a)

  1. >>> a="Hello\
  2. Welcome"
  3. >>> print(a)
>>> a="Hello\
Welcome"
>>> print(a)

Hello      Welcome

6. Accessing a Python String

A string is immutable; it can’t be changed.

>>> a="Dogs" >>> a[0]="H" Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> a[0]="H"

  1. >>> a="Dogs"
  2. >>> a[0]="H"
  3. Traceback (most recent call last):
  4. File "<pyshell#22>", line 1, in <module>
  5. a[0]="H"
>>> a="Dogs"
>>> a[0]="H"
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a[0]="H"

TypeError: ‘str’ object does not support item assignment

But you can access a string.

>>> a="Dogs are love" >>> a

  1. >>> a="Dogs are love"
  2. >>> a
>>> a="Dogs are love"
>>> a

‘Dogs are love’

>>> print(a)>>> print(a)

Dogs are love

a. Displaying a single character- To display a single character from a string, put its index in square brackets. Indexing begins at 0.

>>> a[1]>>> a[1]

‘o’

b. Slicing a string- Sometimes, you may want to display only a part of a string. For this, use the slicing operator [].

>>> a[3:8]>>> a[3:8]

‘s are’

Here, it printed characters 3 to 7, with the indexing beginning at 0.

>>> a[:8]>>> a[:8]

‘Dogs are’

This prints characters from the beginning to character 7.

>>> a[8:]>>> a[8:]

‘ love’

This prints characters from character 8 to the end of the string.

>>> a[:]>>> a[:]

‘Dogs are love’

This prints the whole string.

>>> a[:-2]>>> a[:-2]

‘Dogs are lo’

This prints characters from the beginning to two characters less than the end of the string.

>>> a[-2:]>>> a[-2:]

‘ve’

This prints characters from two characters from the end to the end of the string.

>>> a[-3:-2]>>> a[-3:-2]

‘o’

This prints characters from three characters from the string’s end to two characters from it.

The following codes return empty strings.

>>> a[-2:-2]>>> a[-2:-2]

>>> a[2:2]>>> a[2:2]

7. Python String Concatenation

Concatenation is the operation of joining stuff together. Strings can be joined using the concatenation operator +.

>>> a='Do you see this, ' >>> b='$$?' >>> a+b

  1. >>> a='Do you see this, '
  2. >>> b='$$?'
  3. >>> a+b
>>> a='Do you see this, '
>>> b='$$?'
>>> a+b

‘Do you see this, $$?’

Let’s take another example.

>>> a='10' >>> print(2*a)

  1. >>> a='10'
  2. >>> print(2*a)
>>> a='10'
>>> print(2*a)

1010

Multiplying ‘a’ by 2 returned 1010, and not 20, because ‘10’ is a string, not a number. You cannot concatenate a string to a number.

>>> '10'+10 Traceback (most recent call last): File "<pyshell#49>", line 1, in <module>

  1. >>> '10'+10
  2. Traceback (most recent call last):
  3. File "<pyshell#49>", line 1, in <module>
>>> '10'+10
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>

’10’+10

TypeError: must be str, not int

8. Python String Formatters

Sometimes, you may want to print variables along with a string. You can either use commas, or use string formatters for the same.

>>> city='Ahmedabad' >>> print("Age",21,"City",city)

  1. >>> city='Ahmedabad'
  2. >>> print("Age",21,"City",city)
>>> city='Ahmedabad'
>>> print("Age",21,"City",city)

Age 21 City Ahmedabad

a. f-strings- The letter ‘f’ precedes the string, and the variables are mentioned in curly braces in their places.

>>> name='Ayushi'
>>> print(f"It isn't {name}'s birthday")
  1. >>> name='Ayushi'
  2. >>> print(f"It isn't {name}'s birthday")
>>> name='Ayushi'
>>> print(f"It isn't {name}'s birthday")

It isn’t Ayushi’s birthday

Notice that because we wanted to use two single quotes in the string, we delimited the entire string with double quotes instead.

b. format() method- You can use the format() method to do the same. It succeeds the string, and has the variables as arguments separated by commas. In the string, use curly braces to posit the variables. Inside the curly braces, you can either put 0,1,.. or the variables. When doing the latter, you must assign values to them in the format method.

>>> print("I love {0}".format(a))>>> print("I love {0}".format(a))

I love dogs

>>> print("I love {a}".format(a='cats'))>>> print("I love {a}".format(a='cats'))

I love cats

The variables don’t have to defined before the print statement.

>>> print("I love {b}".format(b='ferrets'))>>> print("I love {b}".format(b='ferrets'))

I love ferrets

c. % operator- The % operator goes where the variables go in a string. %s is for string. What follows the string is the operator and variables in parentheses/in a tuple.

>>> print("I love %s and %s" %(a,b))>>> print("I love %s and %s" %(a,b))

I love dogs and cats

Other options include:

%d – for integers

%f – for floating-point numbers

9. Python Escape Sequences

In a string, you may want to put a tab, a linefeed, or other such things. Escape sequences allow us to do this. An escape sequence is a backslash followed by a character, depending on what you want to do. Python supports the following sequences.

  • \n – linefeed
  • \t – tab

>>> print("hell\to")>>> print("hell\to")

hell         o

  • \\ – backslash

Since a backslash may be a part of an escape sequence, so, a backslash must be escaped by a backslash too.

  • \’ – A single quote can be escaped by a backslash. This lets you use single quotes freely in a string.
  • \” – Like the single quote, the double quote can be escaped too.

10. Python String Functions

Python provides us with a number of functions that we can apply on strings or to create strings.

a. len()- The len() function returns the length of a string.

>>> a='book' >>> len(a)

  1. >>> a='book'
  2. >>> len(a)
>>> a='book'
>>> len(a)

4

You can also use it to find how long a slice of the string is.

>>> len(a[2:])>>> len(a[2:])

2

b. str()- This function converts any data type into a string.

>>> str(2+3j)>>> str(2+3j)

‘(2+3j)’

>>> str(['red','green','blue'])>>> str(['red','green','blue'])

“[‘red’, ‘green’, ‘blue’]”

c. lower() and upper()- These methods return the string in lowercase and uppercase, respectively.

>>> a='Book' >>> a.lower()

  1. >>> a='Book'
  2. >>> a.lower()
>>> a='Book'
>>> a.lower()

‘book’

>>> a.upper()>>> a.upper()

‘BOOK’

d. strip()- It removes whitespaces from the beginning and end of the string.

>>> a='  Book ' >>> a.strip()

  1. >>> a=' Book '
  2. >>> a.strip()
>>> a='  Book '
>>> a.strip()

‘Book’

e. isdigit()- Returns True if all characters in a string are digits.

>>> a='777' >>> a.isdigit()

  1. >>> a='777'
  2. >>> a.isdigit()
>>> a='777'
>>> a.isdigit()

True

>>> a='77a' >>> a.isdigit()

  1. >>> a='77a'
  2. >>> a.isdigit()
>>> a='77a'
>>> a.isdigit()

False

f. isalpha()- Returns True if all characters in a string are characters from an alphabet.

>>> a='abc' >>> a.isalpha()

  1. >>> a='abc'
  2. >>> a.isalpha()
>>> a='abc'
>>> a.isalpha()

True

>>> a='ab7' >>> a.isalpha()

  1. >>> a='ab7'
  2. >>> a.isalpha()
>>> a='ab7'
>>> a.isalpha()

False

g. isspace()- Returns True if all characters in a string are spaces.

>>> a='   ' >>> a.isspace()

  1. >>> a=' '
  2. >>> a.isspace()
>>> a='   '
>>> a.isspace()

True

>>> a=' \'  ' >>> a.isspace()

  1. >>> a=' \' '
  2. >>> a.isspace()
>>> a=' \'  '
>>> a.isspace()

False

h. startswith()- It takes a string as an argument, and returns True is the string it is applied on begins with the string in the argument.

>>> a.startswith('un')>>> a.startswith('un')

True

i. endswith()- It takes a string as an argument, and returns True if the string it is applied on ends with the string in the argument.

>>> a='therefore' >>> a.endswith('fore')

  1. >>> a='therefore'
  2. >>> a.endswith('fore')
>>> a='therefore'
>>> a.endswith('fore')

True

j. find()- It takes an argument and searches for it in the string on which it is applied. It then returns the index of the substring.

>>> 'homeowner'.find('meow')>>> 'homeowner'.find('meow')

2

If the string doesn’t exist in the main string, then the index it returns is 1.

>>> 'homeowner'.find('wow')>>> 'homeowner'.find('wow')

-1

k. replace()- It takes two arguments. The first is the substring to be replaced. The second is the substring to replace with.

>>> 'banana'.replace('na','ha')>>> 'banana'.replace('na','ha')

‘bahaha’

l. split()- It takes one argument. The string is then split around every occurrence of the argument in the string.

>>> 'No. Okay. Why?'.split('.')>>> 'No. Okay. Why?'.split('.')

[‘No’, ‘ Okay’, ‘ Why?’]

m. join()- It takes a list as an argument, and joins the elements in the list using the string it is applied on.

>>> "*".join(['red','green','blue'])>>> "*".join(['red','green','blue'])

‘red*green*blue’

11. Python String Operations

a. Comparison

Strings can be compared using the relational operators.

>>> 'hey'<'hi'>>> 'hey'<'hi'

True

‘hey’ is lesser than ‘hi lexicographically (because i comes after e in the dictionary)

>>> a='check' >>> a=='check'

  1. >>> a='check'
  2. >>> a=='check'
>>> a='check'
>>> a=='check'

True

>>> 'yes'!='no'>>> 'yes'!='no'

True

b. Arithmetic

Some arithmetic operations can be applied on strings.

>>> 'ba'+'na'*2>>> 'ba'+'na'*2

‘banana’

c. Membership

The membership operators of Python can be used to check if string is a substring to another.

>>> 'na' in 'banana'>>> 'na' in 'banana'

True

>>> 'less' not in 'helpless'>>> 'less' not in 'helpless'

False

d. Identity

Python’s identity operators ‘is’ and ‘is not’ can be used on strings.

>>> 'Hey' is 'Hi'>>> 'Hey' is 'Hi'

False

>>> 'Yo' is not 'yo'>>> 'Yo' is not 'yo'

True

e. Logical

Python’s and, or, and not operators can be applied too. An empty string has a Boolean value of False.

1. and- If the value on the left is True it returns the value on the right. Otherwise, the value on the left is False, it returns False.

>>> '' and '1'>>> '' and '1'

>>> '1' and ''>>> '1' and ''

2. or- If the value on the left is True, it returns True. Otherwise, the value on the right is returned.

3. not- As we said earlier, an empty string has a Boolean value of False.

>>> not('1')>>> not('1')

False

>>> not('')>>> not('')

True