0% found this document useful (0 votes)
10 views

Python Session3 Strings Lists

Uploaded by

docogo5352
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Session3 Strings Lists

Uploaded by

docogo5352
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Program - The current population of a town is 10000.

The population
of the town is increasing at the rate of 10% per year. You have to write
a program to find out the population at the end of each of the last 10
years.
# Code here
curr_pop = 10000

for i in range(10,0,-1):
print(i,curr_pop)
curr_pop = curr_pop/1.1

10 10000
9 9090.90909090909
8 8264.462809917353
7 7513.148009015775
6 6830.134553650703
5 6209.213230591548
4 5644.739300537771
3 5131.5811823070635
2 4665.07380209733
1 4240.976183724845

Sequence sum
1/1! + 2/2! + 3/3! + ...

# Code here

n = int(input('enter n'))

result = 0
fact = 1

for i in range(1,n+1):
fact = fact * i
result = result + i/fact

print(result)

enter n2
2.0
Nested Loops
# Examples -> unique pairs

for i in range(1,5):
for j in range(1,5):
print(i,j)

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
4 1
4 2
4 3
4 4

Pattern 1
*** **** ***

# code here

rows = int(input('enter number of rows'))

for i in range(1,rows+1):
for j in range(1,i+1):
print('*',end='')
print()

enter number of rows10


*
**
***
****
*****
******
*******
********
*********
**********
Pattern 2
1 121 12321 1234321

# Code here
rows = int(input('enter number of rows'))

for i in range(1,rows+1):
for j in range(1,i+1):
print(j,end='')
for k in range(i-1,0,-1):
print(k,end='')

print()

enter number of rows4


1
121
12321
1234321

Loop Control Statement


• Break
• Continue
• Pass
for i in range(1,10):
if i == 5:
break
print(i)

1
2
3
4

lower = int(input('enter lower range'))


upper = int(input('enter upper range'))

for i in range(lower,upper+1):
for j in range(2,i):
if i%j == 0:
break
else:
print(i)

enter lower range10


enter upper range100
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

# Continue
for i in range(1,10):
if i == 5:
continue
print(i)

1
2
3
4
6
7
8
9

for i in range(1,10):
pass

Strings are sequence of Characters

In Python specifically, strings are a sequence of Unicode Characters

• Creating Strings
• Accessing Strings
• Adding Chars to Strings
• Editing Strings
• Deleting Strings
• Operations on Strings
• String Functions

Creating Stings
s = 'hello'
s = "hello"
# multiline strings
s = '''hello'''
s = """hello"""
s = str('hello')
print(s)

hello

"it's raining outside"

{"type":"string"}

Accessing Substrings from a String


# Positive Indexing
s = 'hello world'
print(s[41])

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
<ipython-input-61-633ba99ed6e5> in <module>
1 # Positive Indexing
2 s = 'hello world'
----> 3 print(s[41])

IndexError: string index out of range

# Negative Indexing
s = 'hello world'
print(s[-3])

# Slicing
s = 'hello world'
print(s[6:0:-2])

wol

print(s[::-1])

dlrow olleh
s = 'hello world'
print(s[-1:-6:-1])

dlrow

Editing and Deleting in Strings


s = 'hello world'
s[0] = 'H'

# Python strings are immutable

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-80-0c8a824e3b73> in <module>
1 s = 'hello world'
----> 2 s[0] = 'H'

TypeError: 'str' object does not support item assignment

s = 'hello world'
del s
print(s)

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
<ipython-input-81-9ae37fbf1c6c> in <module>
1 s = 'hello world'
2 del s
----> 3 print(s)

NameError: name 's' is not defined

s = 'hello world'
del s[-1:-5:2]
print(s)

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
<ipython-input-82-d0d823eafb6b> in <module>
1 s = 'hello world'
----> 2 del s[-1:-5:2]
3 print(s)

TypeError: 'str' object does not support item deletion


Operations on Strings
• Arithmetic Operations
• Relational Operations
• Logical Operations
• Loops on Strings
• Membership Operations
print('delhi' + ' ' + 'mumbai')

delhi mumbai

print('delhi'*5)

delhidelhidelhidelhidelhi

print("*"*50)

**************************************************

'delhi' != 'delhi'

False

'mumbai' > 'pune'


# lexiographically

False

'Pune' > 'pune'

False

'hello' and 'world'

{"type":"string"}

'hello' or 'world'

{"type":"string"}

'' and 'world'

{"type":"string"}

'' or 'world'

{"type":"string"}

'hello' or 'world'

{"type":"string"}

'hello' and 'world'


{"type":"string"}

not 'hello'

False

for i in 'hello':
print(i)

h
e
l
l
o

for i in 'delhi':
print('pune')

pune
pune
pune
pune
pune

'D' in 'delhi'

False

Common Functions
• len
• max
• min
• sorted
len('hello world')

11

max('hello world')

{"type":"string"}

min('hello world')

{"type":"string"}
sorted('hello world',reverse=True)

['w', 'r', 'o', 'o', 'l', 'l', 'l', 'h', 'e', 'd', ' ']

Capitalize/Title/Upper/Lower/Swapcase
s = 'hello world'
print(s.capitalize())
print(s)

Hello world
hello world

s.title()

{"type":"string"}

s.upper()

{"type":"string"}

'Hello Wolrd'.lower()

{"type":"string"}

'HeLlO WorLD'.swapcase()

{"type":"string"}

Count/Find/Index
'my name is nitish'.count('i')

'my name is nitish'.find('x')

-1

'my name is nitish'.index('x')

----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
<ipython-input-121-12e2ad5b75e9> in <module>
----> 1 'my name is nitish'.index('x')

ValueError: substring not found


endswith/startswith
'my name is nitish'.endswith('sho')

False

'my name is nitish'.startswith('1my')

False

format
name = 'nitish'
gender = 'male'

'Hi my name is {1} and I am a {0}'.format(gender,name)

{"type":"string"}

isalnum/ isalpha/ isdigit/ isidentifier


'nitish1234%'.isalnum()

False

'nitish'.isalpha()

True

'123abc'.isdigit()

False

'first-name'.isidentifier()

False

Split/Join
'hi my name is nitish'.split()

['hi', 'my', 'name', 'is', 'nitish']

" ".join(['hi', 'my', 'name', 'is', 'nitish'])

{"type":"string"}

Replace
'hi my name is nitish'.replace('nitisrgewrhgh','campusx')
{"type":"string"}

Strip
'nitish '.strip()

{"type":"string"}

Example Programs
# Find the length of a given string without using the len() function

s = input('enter the string')

counter = 0

for i in s:
counter += 1

print('length of string is',counter)

enter the stringnitish


length of string is 6

# Extract username from a given email.


# Eg if the email is [email protected]
# then the username should be nitish24singh

s = input('enter the email')

pos = s.index('@')
print(s[0:pos])

enter the [email protected]


support

# Count the frequency of a particular character in a provided string.


# Eg 'hello how are you' is the string, the frequency of h in this
string is 2.

s = input('enter the email')


term = input('what would like to search for')

counter = 0
for i in s:
if i == term:
counter += 1

print('frequency',counter)
enter the emailhi how are you
what would like to search foro
frequency 2

# Write a program which can remove a particular character from a


string.
s = input('enter the string')
term = input('what would like to remove')

result = ''

for i in s:
if i != term:
result = result + i

print(result)

enter the stringnitish


what would like to removei
ntsh

# Write a program that can check whether a given string is palindrome


or not.
# abba
# malayalam

s = input('enter the string')


flag = True
for i in range(0,len(s)//2):
if s[i] != s[len(s) - i -1]:
flag = False
print('Not a Palindrome')
break

if flag:
print('Palindrome')

enter the stringpython


Not a Palindrome

# Write a program to count the number of words in a string without


split()

s = input('enter the string')


L = []
temp = ''
for i in s:

if i != ' ':
temp = temp + i
else:
L.append(temp)
temp = ''

L.append(temp)
print(L)

enter the stringhi how are you


['hi', 'how', 'are', 'you']

# Write a python program to convert a string to title case without


using the title()
s = input('enter the string')

L = []
for i in s.split():
L.append(i[0].upper() + i[1:].lower())

print(" ".join(L))

enter the stringhi my namE iS NitiSh


Hi My Name Is Nitish

# Write a program that can convert an integer to string.

number = int(input('enter the number'))

digits = '0123456789'
result = ''
while number != 0:
result = digits[number % 10] + result
number = number//10

print(result)
print(type(result))

enter the number345


345
<class 'str'>

You might also like