Strings in Python Class 11 Notes

Share with others

Strings in Python Class 11 Notes, Strings are basically used for storing and manipulating text. This chapter covers how to create strings, about indexing, slicing and built-in string methods. This note will be helpful for understanding the string concept with real-world examples.

Strings in Python Class 11 Notes

Strings

A string is a group of one or more characters in sequence. A letter, number, space, or any other sign may be used as the character in this situation. One or more characters can be enclosed in a single, double, or triple quote to produce a string.

Example – 

str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!"""
str4 = '''Hello World!''

Note – Python accepts single (‘), double (“), triple (”’) or triple(“””) quotes to denote string literals.

Single (‘) and Double (“) Quotes

  • Both quotes are used for short text.
  • Both quotes are similar.
  • Inside the double quotes, single quotes can be used; for example, text2 = “I love the ‘Python’ language.”

Triple Quotes (”’) or (“””)

  • Both quotes are used for multi-line strings.
  • Both quotes can contain special characters like TAB (\t) or NEWLINE (\n).

Accessing Characters in a String

  • Strings are stored as sequences of characters in memory.
  • The string once created cannot be changed. It is immutable.
  • Each character has an index, starting from (0) for the first character which is known as positive index.
  • Negative indexing helps to access characters from the end (-1) which is known as negative index.
string in python

String is Immutable

A string is an immutable data type. It means that the contents of the string cannot be changed after it has been created. An attempt to do this would lead to an error.

>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'

Output:
TypeError: 'str' object does not support item assignment

String Operations

A string is a group of letters and numbers. Concatenation, repetition, membership, and slicing are just a few of the operations Python supports on the string data type. The following subsections provide explanations of these procedures along with pertinent examples.

Concatenation

To concatenate means to join. Python allows us to join two strings using concatenation operator plus which is denoted by symbol +.

str1 = 'Hello'
str2 = 'World!'
print(str1 + str2)

Output:
Hello World!
Repetition

Python allows us to repeat the given string using repetition operator which is denoted by symbol *.

str1 = 'Hello'
print(str1 * 2)

Output:
HelloHello
Membership

Python has two membership operators ‘in’ and ‘not in’. The ‘in’ operator takes two strings and returns True if the first string appears as a substring in the second string, otherwise it returns False.

In
str1 = 'Hello World!'
print('W' in str1)

Output:
True
Not In
str1 = 'Hello World!'
print('My' not in str1)

Output:
True
Slicing

In Python, to access some part of a string or substring, we use a method called slicing. This can be done by specifying an index range. Given a string str1, the slice operation str1[n:m].

str1 = 'Hello World!'
print(str1[1:5])

Output:
ello

Traversing a String

We can access each character of a string or traverse a string using for loop and while loop.

String Traversal Using for Loop:
str1 = 'Hello World!'
for ch in str1:
    print(ch, end='')

Output:
Hello World!

In the above code, the loop starts from the first character of the string str1 and automatically ends when the last character is accessed.

String Traversal Using while Loop:
str1 = 'Hello World!'
index = 0

while index < len(str1):
    print(str1[index], end='')
    index += 1

Output:
Hello World!

Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.

String Methods and Built-in Functions

There are numerous built-in functions in Python that let us operate with strings. a few of the most popular built-in functions for manipulating strings.

len()

Returns the length of the given string

str1 = 'Hello World!'
print(len(str1))

Output:
12
title()

Returns the string with first letter of every word in the string in uppercase and rest in lowercase

str1 = 'hello WORLD!'
print(str1.title())

Output:
Hello World!
lower()

Returns the string with all uppercase letters converted to lowercase

str1 = 'hello WORLD!'
print(str1.lower())

Output:
hello world!
upper()

Returns the string with all lowercase letters converted to uppercase

str1 = 'hello WORLD!'
print(str1.upper())

Output:
HELLO WORLD!
count(str, start, end)

Returns number of times substring str occurs in the given string. If we do not give start index and end index then searching starts from index 0 and ends at length of the string.

str1 = 'Hello World! Hello\nHello'
print(str1.count('Hello', 12, 25))
print(str1.count('Hello'))

Output:
2
3
find(str, start, end)

Returns the first occurrence of index of substring str occurring in the given string. If we do not give start and end then searching starts from index 0 and ends at length of the string. If the substring is not present in the given string, then the function returns -1

str1 = 'World! Hello Hello'
print(str1.find('Hello'))

Output:
7
index(str, start, end)

Same as find() but raises an exception if the substring is not present in the given string

>>> str1 = ‘Hello World! Hello
Hello’
>>> str1.index(‘Hello’)
0
>>> str1.index(‘Hee’)
ValueError: substring not found

endswith()

Returns True if the given string ends with the supplied substring otherwise returns False.

str1 = "Hello World!"
print(str1.endswith("World!"))
print(str1.endswith("lde"))

Output:
True
False
startswith()

Returns True if the given string starts with the supplied substring otherwise returns False.

str1 = "Hello World!"
print(str1.startswith("He"))
print(str1.startswith("Hee"))

Output:
True
False
isalnum()

Returns True if characters of the given string are either alphabets or numeric. If whitespace or special symbols are part of the given string or the string is empty it returns False

str1 = "HelloWorld"
str2 = "Hello World"
print(str1.isalnum())
print(str2.isalnum())

Output:
True
False
islower()

Returns True if the string is non-empty and has all lowercase alphabets, or has at least one character as lowercase alphabet and rest are non-alphabet characters

str1 = 'hello world!'
str2 = 'Hello World!'
print(str1.islower())
print(str2.islower())

Output:
True
False
isupper()

Returns True if the string is non-empty and has all uppercase alphabets, or has at least one character as uppercase character and rest are non-alphabet characters

str1 = 'HELLO WORLD!'
str2 = 'Hello World!'
print(str1.isupper())
print(str2.isupper())

Output:
True
False
isspace()

Returns True if the string is non-empty and all characters are white spaces (blank, tab, newline etc.)

str1 = ' \n \t \r'
str1 = 'Hello \n'
print(str1.isspace())
print(str1.isspace())

Output:
True
False
istitle()

Returns True if the string is non-empty and title case, i.e., the first letter of every word in the string in uppercase and rest in lowercase

str1 = 'Hello World!'
str1 = 'hello World!'
print(str1.istitle())
print(str2.istitle())

Output:
True
False
lstrip()

Returns the string after removing the spaces only on the left of the string

str1 = '   Hello World!'
print(str1.lstrip())

Output:
Hello World!
rstrip()

Returns the string after removing the spaces only on the right of the string

str1 = "Hello World!   "
print(str1.rstrip())

Output:
Hello World!
strip()

Returns the string after removing the spaces both on the left and the right of the string

str1 = "   Hello World!   "
print(str1.strip())

Output:
Hello World!
replace(oldstr, newstr)

Replaces all occurrences of old string with the new string

str1 = 'Hello World!'
print(str1.replace('World', 'Country'))

Output:
Hello Country!
join()

Returns a string in which the characters in the string have been joined by a separator

str1 = "HelloWorld!"
str2 = "-"
print(str2.join(str1))

Output:
H-e-l-l-o-W-o-r-l-d-!
partition()

Partitions the given string at the first occurrence of the substring (separator) and returns the string partitioned into three parts.

  • Substring before the separator
  • Separator
  • Substring after the separator

If the separator is not found in the string, it returns the whole string itself and two empty strings

str1 = 'India is a Great Country'
print(str1.partition('is'))

Output:
('India ', 'is', ' a Great Country')
split()

Returns a list of words delimited by the specified substring. If no delimiter is given then words are separated by space.

str1 = 'India is a Great Country'
print(str1.split())

Output:
['India', 'is', 'a', 'Great', 'Country']

Computer Science Class 11 Notes important links

Disclaimer: We have taken an effort to provide you with the accurate handout of “Strings in Python Class 11 Notes“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above CBSE study material present on our websites is for education purpose, not our copyrights. All the above content and Screenshot are taken from Computer Science Class 11 CBSE Textbook, Sample Paper, Old Sample Paper, Board Paper, NCERT Textbook and Support Material which is present in CBSEACADEMIC website, This Textbook and Support Material are legally copyright by Central Board of Secondary Education. We are only providing a medium and helping the students to improve the performances in the examination. 

Images and content shown above are the property of individual organizations and are used here for reference purposes only.

For more information, refer to the official CBSE textbooks available at cbseacademic.nic.in


Share with others

Leave a Comment