Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views21 pages

Strings

This document provides a comprehensive overview of string handling in Python, covering topics such as declaration, formatting, accessing elements, and string operations. It explains various methods for manipulating strings, including indexing, slicing, and using string functions, as well as the immutability of strings. Additionally, it includes examples and programming exercises to reinforce the concepts discussed.

Uploaded by

astaaunii453
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)
13 views21 pages

Strings

This document provides a comprehensive overview of string handling in Python, covering topics such as declaration, formatting, accessing elements, and string operations. It explains various methods for manipulating strings, including indexing, slicing, and using string functions, as well as the immutability of strings. Additionally, it includes examples and programming exercises to reinforce the concepts discussed.

Uploaded by

astaaunii453
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
You are on page 1/ 21

STRINGS

LEARNING OBJECTIVES

At the end of this chapter students will be able to understand

● Declaration of strings
● Formatting of strings
● Accessing elements from string
○ Indexing method
○ Slicing method
● Addition to a string
● Updating a string
● Deleting a string
● Traversing a string
○ Using for loop
○ using while loop
● String operators
○ Concatenation
○ Repetition
○ Membership (in/not in)
○ Raw String
● String functions
○ len(), capitalize(), istitle(), title()
○ isalnum(), isalpha(), isdigit()
○ lower(), upper(), islower(), isupper(), swapcase()
○ find(sub[, start[, end]]), index(value, start, end), count(substring, start, end)
○ strip(), lstrip(), rstrip(), isspace()
○ join(), replace(old,new), partition(sep), split([sep[, maxsplit]])

Python string is a sequence of characters enclosed in quotes.

● Strings are immutable i.e. the contents of the string cannot be changed after it is created.
● Python does not support character data type. A string of size 1 can be treated as characters.
DECLARING STRINGS

Strings are declared/created by enclosing sequence of characters in quotes.

NOTE : Python treats single quotes the same as double quotes. Triple quotes can be used in Python but
they are generally used to represent multiline strings and docstrings.

EXAMPLE

>>> str1="Keep your city clean and green"

>>> print(str1)

Keep your city clean and green

>>> my_str = """Hello, welcome to

the world of Python"""

>>> print(my_str)

Hello, welcome to

the world of Python

USING INPUT() METHOD

The input() method is used to input string from a keyboard and assign to the string variable present on the
left hand side.

>>> str5=input("Enter string")

Enter string "I am learning Python"


>>> print(str5)
"I am learning Python"

Here the string entered "I am learning Python" is assigned to string variable str5.
NOTE : It is mandatory to enclose the given input i.e. hello in quotes otherwise Python interpreter will not
be able to associate appropriate data type with the entered data and results in error.

Python String Formatting

Escape Sequence

If special characters like single quotes, double quotes, forward and backward slash etc. are part of a string
then it poses problems.

One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash.

Escape Sequence in Python

quence n

and newline ignored

te
space

feed

eed

age Return

zontal Tab

cal Tab

>>> print('''Ram said, "What's the matter''')

Ram said, "What's the matter''

Here string is enclosed in triple quotes so we can easily use any special character.

>>> print("Ram said, \"what's the matter\" ")


Ram said, "what's the matter"

Here string is enclosed in double quotes so need to use escape sequence character \ before all double
quotes appearing in the string.

>>> print ('Ram said, "What\'s the matter" ')


Ram said, "What's the matter"
Here string is enclosed in single quotes so need to use escape sequence character \ before all single
quotes appearing in the string.

>>> print("We must keep our city \n CLEAN and GREEN")

We must keep our city

CLEAN and GREEN

Here \n is a new line character and text following it comes to the next line. Thus " CLEAN and GREEN" is
coming to the next line.

ACCESSING ELEMENTS FROM STRING

INDEXING METHOD

Elements of a string can be accessed using an indexing method.

● String indices start at 0.


● The string index has to be a positive or negative integer value or an expression which evaluates to
an integer value.
● Positive value of index means counting forward from beginning of the string and negative value
means counting backward from end of the string.
● An Index Error appears, if we try to access element that does not exist in the string.

If the total number of elements in the string is max, then:

e the list
Considering the following example:

str1= "Hello Python"


SLICING METHOD

Slicing is used to retrieve a subset of values. A slice of a string is basically its sub-string.

SYNTAX

string-name[start: stop: step]

where

start is the starting point

stop is the stopping point

step is the step size - also known as stride

NOTE:

● If you omit first index, slice starts from “0” and omitting of stop will take it to end. Default value of
step is 1.
● It includes the first element but excludes the last element.

EXAMPLE

Consider a string str1 with values

str1= "Hello Python"

on'
m beginning till end in step 2)

m end till beginning in step 2)

ADDITION TO A STRING

We can only add characters to the end of the string using a concatenation operator '+'. It is not possible to
add new characters in the beginning or in between the existing string.

>>> str1="Keep your city clean and green."

>>> str1=str1+" Thanks"


>>> print(str1)

Keep your city clean and green. Thanks

UPDATING A STRING

Strings are immutable. This means that elements of a string cannot be changed once it has been
assigned. We can simply reassign different strings to the same name.

EXAMPLE

>>> str="aasdfd"

>>> str[1]='q'

Traceback (most recent call last):

File "<pyshell#62>", line 1, in <module>

str[1]='q'

TypeError: 'str' object does not support item assignment

>>> str="aasdfd"

>>> str="Learning Python"

>>> print(str)

Learning Python

DELETING A STRING

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the
keyword del.

EXAMPLE

>>> del(str5[1]) # deleting an element from a string

Traceback (most recent call last):


File "<pyshell#104>", line 1, in <module>

del(str5[1])

TypeError: 'str' object doesn't support item deletion

>>> del str1 # deleting a string

>>> print(str1)

Traceback (most recent call last):

File "<pyshell#102>", line 1, in <module>

print(str1)

NameError: name 'str1' is not defined

TRAVERSING A STRING

Traversing a string means accessing all the elements of the string one after the other by using the
index/subscript. A string can be traversed using either a for loop or a while loop.

TRAVERSING A STRING USING FOR LOOP

EXAMPLE

str1="Hello Python"

for i in str1:

print(i)

OUTPUT

l
l

TRAVERSING A STRING USING WHILE LOOP

EXAMPLE

str1="Hello Python"

i=0

while i<len(str1):

print(str1[i])

i=i+1

OUTPUT

o
P

STRING OPERATORS

Consider the following declarations:

>>> str1="Tech"

>>> str2="Era"

tion (+) - Joins the strings on either sideTech"

Era"

tr2

tr2+str1

tr3)
(*) - Concatenates/multiplies multiple cop
given number of times

ip (in) - Returns true if a character exists tr1

r1

ip (not in) - Returns true if a character doin str1


given string

n str1

STRIING FUNCTIONS

Note: For all the functions except len() function, import string statement is required for successful
execution.

lstrip([char])

ION

TechEra'
length of the string. 3)

tr4.capitalize())

tring with the first letter in uppercase and018


wercase.

ech era *2018*'

e if the string contains only letters and digtr5.isalnum())


se ,If the string contains any special chara

ech era *2018*'

e if the string contains only alphabets othtr5.isalpha())


se.

TechEra'

tr3.isalpha())

2345'

e if the string contains only numbers. Othtr6.isdigit())


se.
tr3.lower())

copy of the string with all the letters in lo

tr3.upper())

copy of the string with all the letters in up

ech era *2018*'

e if the string is in lowercase. tr5.islower())

ech era *2018*'

e if the string is in uppercase. tr5.isupper())

start[, end]]) ech era *2018*'

he first occurrence of the substring in thend('ch')


urns the index at which the substring star
the substring does occur in the string.

nd('*')
parameter is omitted, the function starts th
ginning.

ring is present multiple times in the string,


es the position of first occurrence. nd('*', 10)
]) tech era *2018* '

string after removing the space(s) on therip()


f the string. The parameter char is optiona
d to specify the a set of characters to be 2018*'
r
right side of the string.
ech * era * tech'

rip("tech")

*'

r]) tech era *2018* '

string after removing the space(s) on thetrip()


parameter char is optional, which can be
a set of characters to be removed from le2018* '

r]) tech era *2018* '

string after removing the space(s) on thetrip()


The parameter char is optional, which can
a set of characters to be removed from rig2018*'

e if the string contains only white spacesstr.isspace())


ntains one character
tech era *2018* '

space()

ech era *2018*'

string in title case le()

2018*'

ech era *2018*'

e if the string is title cased otherwise retutitle()

Tech Era *2018*'

title()

Tech Era *2018*'

tring in which the string elements have be


#'
tor.
in(str5)

#E#r#a# #*#2#0#1#8#*'
oin(iterable)
s a string

be a List, Tuple, String or Dictionary

) wapcase()

e for all letters in string. *2018*'

d,new) earning Python"

n replaces all the occurrences of the old str.replace('n', '@'))


ng.
Pytho@

ep) tition('ing')

n partitions the strings at the first occurreng', ' Python')


nd returns the strings partition in three pa
separator, the separator itself, and the partition('king')
f the separator is not found, returns the st
two empty strings Python', '', '')

maxsplit]]) Tech Era *2018*'

ring into list of substrings using the separ


plit('e')

a *2018*']

nal. It specifies the separator to use when


plit('*')
By default, any whitespace is a separator
optional. It Specifies how many splits to d, '2018', '']
which is "all occurrences"
Tach Era *2018*'

plit('a')
' *2018*']

plit('a',1)
a *2018*']

plit('a',2)
' *2018*']

plit('a',3)
' *2018*']

string, start, end) ike dancing and singing"

a character or a substring in the given str


unt("ing")
w many times the character/substring is pr

string whose count is to be found.


unt("ing",15)
onal) - starting index within the string whe

nal) - ending index within the string where

e, start, end) ike dancing and singing"

st occurrence of the specified value. ex("ing")

quired. The value to search for


onal) - starting index within the string wheex("ing",15)

nal) - ending index within the string where


ex("k",15)

(most recent call last): File "", line 1, in


k",15) ValueError: substring not found

ndex() method is almost the same as the find() method. The only difference is that
urns -1 if the value is not found and the index() method will raise an exception.

PROGRAM1:

WAP to input a string and check whether it is a palindrome or not.

str=input("Enter a string")

l=len(str)

beg=0

end=l-1

while(beg<=end):

if(str[beg]==str[end]):

beg=beg+1

end=end-1

else:

print("It is not a palindrome")

break
else:

print("It is a palindrome")

OUTPUT

Enter a string madam

It is a palindrome

PROGRAM2

Write a script to input a big string ad a small string and display the position of small string in big
string.

import string

str1=input("Enter big string")

str2=input("Enter small string")

k=str1.find(str2)

if k>=0:

print(" substring is present at position", k)

else:

print("substring is not present")

OUTPUT

Enter big string my name is Raman

Enter small string name

substring is present at position 4

You might also like