0% found this document useful (0 votes)
3 views9 pages

Unit 7 Strings in Python

This document provides an overview of strings in Python, detailing their definition, creation, and manipulation. It covers string indexing, slicing, multiline strings, escape characters, built-in functions, and membership operators. Examples are provided throughout to illustrate the concepts discussed.

Uploaded by

ayaanrafiq976
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Unit 7 Strings in Python

This document provides an overview of strings in Python, detailing their definition, creation, and manipulation. It covers string indexing, slicing, multiline strings, escape characters, built-in functions, and membership operators. Examples are provided throughout to illustrate the concepts discussed.

Uploaded by

ayaanrafiq976
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit -7

Strings in Python

Defining a String :

A String is an immutable data type in Python that represents a sequence of characters Each
character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters. Each character has a unique numeric value as per the
UNICODE standard. But, the sequence as a whole, doesn't have any numeric value even if all the
characters are digits. A string in Python is an object of str [Link] are used widely in many
different applications, such as storing and manipulating text data, representing names, addresses,
and other types of data that can be represented as text.
e.g : Our name, say Saleem can be considered a string. Or, Say you live in Kashmir, then Kashmir
is a string.
→ Python does not have a character data type, a single character is simply a string with a length of 1.

Creating a string and assign it to a variable :


Strings in Python can be created using single quotes (‘ ‘), double quotes (” “), and triple double
quotes (“”” “””). The triple quotes can be used to declare multiline strings in Python.
e.g : String1 = 'Welcome to the Python'
print("String with the use of Single Quotes: ")
print(String1)

String1 = "I'm a Student"


print("\nString with the use of Double Quotes: ")
print(String1)

String1 = '''I'm a student and I read in 11 th class"'''


print("\nString with the use of Triple Quotes: ")
print(String1)

String1 = '''Help
me
Out'''
print("\nCreating a multiline String: ")

OUTPUT :

e.g : String with the use of Single Quotes:


‘Welcome to the Python’

String with the use of Double Quotes:


‘I'm a Student’
String with the use of Triple Quotes:
‘I'm a student and I read in 11 th class’

Creating a multiline String:


‘Help
me
Out’

Accessing characters ( indexing ) in Python String :


As we know in Python, a string is an ordered sequence of Unicode characters. Each character in the
string has a unique index in the sequence. The index starts with 0 and keeps on incrementing towards
the end of string. If we take length of string to be len , then we can start positive index from left to
right starting from ‘0’ and ends at len-1 (index increments ) and negative index from right to left
starting from ‘-1’ to the length of string (the index decrements)

e.g : Str = “ GOOD MORNING” # Length of above string = 12

0 1 2 3 4 5 6 7 8 9 10 11
G O O D M O R N I N G
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Index value should be always an integer. float or other types can result in TypeError. Also if
the index in square brackets exceeds the upper bound, Python raises IndexError.
We can access any individual character from the string by its index. We can use both positive
or negative index to retrieve a character from the string.

>>> str[0] will give output as ‘G’


>>> str[3] will give output as ‘D’
>>> str[4] will give output as ‘ ’

>>> str[-12] will also give output as ‘G’


>>> str[ -9 ] will also give output as ‘D’
>>> str[-8 ] will also give output as ‘ ’
Slicing : String slicing in Python is about obtaining a sub-string from the give String .It can be done
by using a Slicing operator, i.e., a colon (:) or by using the in-build slice( ) method.
1. Using slicing operator : Syntax
String_name [ start ; end ; step]
The start is inclusive and is the index of the first character of the desired slice. The end is exclusive
and is the index of the character next to the last in the desired string.
E.g Str = “ GOOD MORNING”

0 1 2 3 4 5 6 7 8 9 10 11
G O O D M O R N I N G
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Slice from the start : ( using positive indexing )


1. str [0:12:1] will give output as GOOD MORNING

2. str[0:12] will also output as GOOD MORNING

3. str[::] will also output as GOOD MORNING –It indicates all operands are optional

4. str[:] will also output as GOOD MORNING

5. str [5:] will give output as MORNING

6. str [0:12:2] will give output as GO ONN adjacent element will be skipped since
step value is 2.
Slice from the start : ( using negative indexing )
1. str [-12:] will give output as GOOD MORNING

2. str [-12:-8] will give output as GOOD

3. str [:-1] will give output as GOOD MORNIN

4. str [::-1] will reverse the string as GNINROM DOOG


The left operand must be smaller than the operand on right, for getting a substring of the original
string. Python doesn't raise any error, if the left operand is greater, but returns a null string.
5 str [-12:] will give output as GOOD MORNING
Mutliline Strings : As we know string is a collection of characters (alphabets, numbers,

spaces, etc.). In Python, single line strings are enclosed in either single quotes ('') or double quotes (""),
and they both work in the same way. Multiline strings are a strings that contains several lines, rather
than just one line. There are several ways to create a multiline string in python.

1. Using Triple Quotes

Python provides a default way to write multi-line strings: using triple [Link] can use both
three single quotes or three double quotes at the beginning and end of string . Any quotes, tabs, or
newlines in between the “triple quotes” are considered part of the string.
e.g :
>>> a=”””SHOIB
AHMAD
BHAT”””
>>>. print(a)

OUTPUT :
SHOIB
AHMAD
BHAT

2. Using only escape character

We can use the '\n' escape character to get a new line character and separate the string into
multiple lines. E.g :

>>> a=”SHOIB\n AHMAD \n BHAT”


>>. print(a)

OUTPUT :
SHOIB
AHMAD
BHAT

3. Using Parentheses

The another approach is by using parenthesis and multiple double quotes to separate the lines in the
code. We have to include the entire string inside the parenthesis and after completion of each line we
should add new line inside parentheses character (\n) inside parentheses and add new line.

E.g : >>> a= ( ”SHOIB\n”


“ AHMAD \n”
“ BHAT”)
>>. print(a)

OUTPUT :
SHOIB
AHMAD
BHAT

4. Using backslash

It is similar to the last approach, but here we are not including the parenthesis we include \ after each
new line character to separate the lines of code:.

e.g : >>> a= ”SHOIB\n” \


“ AHMAD \n” \
“ BHAT”
>>. print(a)

OUTPUT :
SHOIB
AHMAD
BHAT

5. Using join() and a list/tuple

In this approach, you can first store the multiline string in a list or tuple, as a list of lines. Then
you can join all the lines with the newline character and the join() string method.

e.g : >>> a = (' SHOIBr',


'AHMAD',
'BHAT')
>> print('\n'.join(a))

OUTPUT :
SHOIB
AHMAD
BHAT

Escape Characters : An escape character allows us to use non graphic characters that
are otherwise impossible to put into a string. Non-graphic characters are those characters which cannot
be directly typed from the keyboard such as carriage return , tab spaces etc.. These non graphic
characters are represented by using escape characters. An escape character is represented by a
backslash (\) followed by the character you want to add to the string. The backslash tells Python that
the quote following it is part of the string. (Despite consisting of two characters, it is commonly
referred to as a singular escape character.) .
Following are some of the escape sequences. :

1. Single Quote (\’)

To use a single quote inside a string, a backslash followed by a single quote makes it valid to be used
in a statement.

E.g :

s='Hello \'Python\''
print (s)
OUPUT : Hello 'Python'

2. Backslash (\)
To use a backslash inside a string, a backslash must be written as usual before the backslash is printed.

E.g :

print(" Printed string is \\")

Output: Printed string is \

3. Newline (\n)

To go to a new line in Python, we can use the newline character \n within a string. When you print a
string that contains the newline character, the output will be split into separate lines at the position of
the newline character.

E.g:-

print("This is the first line.\n This is the second line.")

Output:

This is the first line.


This is the second line.

4. Carriage Return
It is one of the special escape sequences in python that lets us return to the start of the line
overwriting whatever was already written. It is denoted by ‘r’ followed by a backslash.

Example Carriage Return:

print("This is the first line.", end="\r")


print("This is the second line.")

Output:
This is the second line.

5. Tab

A Tab equals eight whitespaces and it can be implemented by writing backslash followed up by t. It is
helpful in separating statements to improve the readability of string.

Example of Tab:

print("First\tSecond\tThird")
print("1\t2\t3")
print("A\tB\tC")

Output:

First Second Third


1 2 3
A B C

6. Backspace

When the \b escape sequence is used within a string, it moves the cursor one position to the left, as a
matter of fact, it erases the character that was previously present at the position.

Example Backspace:

print("abc\bdef")

Output:

abdef

Explanation:
From the above output, we can find that the backspace escape sequence in python can be used to erase
the last typed character in the string, Here, the character was c, which was erased.

Some built in functions :

1. Len( ) : This method is used to retrieve the length of the string.

The len() method determines how many characters are there in the string including punctuation,
space, and all type of special characters. t

Syntax : len(str)

e.g : >>> str = "this is string length example";


>>> print ("Length of the string: ", len(str))
OUTPUT : Length of the string: 29
>>> li = ["Python","Java","CSS","Javascript"] # this is list
>>> print("The length of the given list is:", len(li))
OUTPUT : The length of the given list is:4 ( No of elements)
[Link]( ) : This method is used to convert all the lowercase characters present in a string into
uppercase. However, if there are elements in the string that are already uppercased, the method will
skip through those elements.
Note : This method will not show affect any non-casebased characters like digits and symbols.

Syntax : [Link]()

e.g : >>> str = "this is uppercase string example";


>>> print ([Link] ( ))
OUTPUT : THIS IS UPPERCASE STRING EXAMPLE

>>>str = "This is a digit/symbol string: 781261&*";


>>>print([Link]())

OUTPUT : This is a digit/symbol string: 781261&*

[Link]( ) : The lower() method is a counterpart for the upper() [Link] method
is used to convert all the Uppercase characters present in a string into lowercase. However, if there are
elements in the string that are already lowercased, the method will skip through those elements.

Syntax : [Link]()

e.g : >>> str = "THIS IS LOWERCASE STRING EXAMPLE";


>>> print ([Link] ( ))
OUTPUT : this is uppercase string example

>>> str = "1234567";


>>> print([Link]())

OUTPUT : 1234567

[Link] : This method replaces all occurrences of one substring in a string with another substring.
This method is used to create another string by replacing some parts of the original string, whose gist
might remain unmodified.

For example, in real-time applications, this method can be used to replace multiple same spelling
mistakes in a document at a time.

This replace() method can also replace selected number of occurrences of substrings in a string instead
of replacing them all.

Syntax : [Link](old, new, count)


• old − This is old substring to be replaced.
• new − This is new substring, which would replace old substring.
• count − If this optional argument count is given, only the first count occurrences are replaced.

e.g : >>> str = "Welcome to replace function"


>>> str_replace = [Link]("o", "0")
>>> print("String after replacing: " + str_replace)

OUTPUT : String after replacing: Welc0me t0 replace functi0n

>>> str = "TRAB BRAB TRAB BRAB TRAB BRAB ."


>>> strreplace = [Link]("BRAB", "CRAB", 1)
>>> print("String after replacing: " + strreplace)

OUTPUT : String after replacing: TRAB CRAB TRAB BRAB TRAB BRAB
The return value will be the string obtained after replacing the first
occurrence of string BRAB with CRAB.

>>> str = "Replace C++ with Python"


>>> strreplace = [Link](“C++” ,"PYTHON", 0)
>>> print("String after replacing: " + strreplace)

OUTPUT : Replace C++ with Python

→ This method does not modify the current string, instead of that, it returns the original value.

Membership Operators : in and not in

Python offers two membership operators to check or validate the membership of a value. It
tests for membership in a sequence, such as strings, lists, or tuples.

in operator: The ‘in’ operator is used to check if a character/ substring/ element exists in a sequence
or not. Evaluate to True if it finds the specified element in a sequence otherwise False.
not in operator- Evaluates to true if it does not finds a variable in the specified sequence and false
otherwise.
e.g : >>> a = 10
>>> b = 4
>>> c= 11
>>> l1 = [1,2,3,4,5,11]
>>> a not in l1
True
>>> b not in l1
False
>>> c in l1
>>> true

You might also like