"""
String is alphanumeric set of characters
Strings are enclosed within the single quotes,double quotes, triple
single or triple double quotes.
Triple single or triple double quotes are also called docstrings.
They are used as multiline comments or
multiline inputs.
"""
#Example
a = 'Aarish Biswas'
b = "Ranjoy Biswas"
c = '''Srihan
Kumar
Nath
'''
d = """
Shreyan
Nag
Computer
Classes
"""
"""
Strings are set of immutable characters. That is the characters
cannot be changed on once they are declared
"""
"""
Taking input as String
"""
k = input("Enter your name: ")
print(k)
Enter your name: Aaron Black
Aaron Black
"""
The datatype of String is
<class 'str'>
to check the datatype use type() function
"""
k = "Green Day"
print(type(k))
<class 'str'>
"""
Strings are immutable i.e. each element or word cannot be changed
once declared. Like list
"""
k = "Cat"
k[0] = "B"
print(k)
--------------------------------------------------------------------
-------
TypeError Traceback (most recent
call last)
Cell In[5], line 5
1 """
2 Strings are immutable i.e. each element or word cannot be
changed once declared. Like list
3 """
4 k = "Cat"
----> 5 k[0] = "B"
6 print(k)
TypeError: 'str' object does not support item assignment
"""
Each element of a list can be displayed using the indexes
Each indexes can either be postive or negative
Positive indexes are from 0 to n (n is the number of character - 1)
(Left to Right)
Negative indexes are from Right to Left (Starting from -1)
"""
"""
m = " A p p l e"
+ve index 0 1 2 3 4
-ve index -5 -4 -3 -2 -1
syntax is variable[start:stop:step] by default stop is always
less by 1 than the given value
and step value is always 1 by default. Start value is always the
begining or the starting index 0
"""
m = "Apple"
print(m[0]) #A
print(m[0:]) #Apple
print(m[::]) #Apple
print(m[1:]) #pple
print(m[-4:]) #pple
print(m[-4:4]) #ppl
print(m[::-1]) #elppA
print(m[::-2]) #epA
print(m[-2::-2]) #lp
#length of the string
m = input("Enter a string: ")
print(len(m))
Enter a string: Quick Brown Fox Jumps Over The Lazy Dog
39
#Traversing a string
#Method 1
m = "Good Evening"
for i in m:
print(i,end=' ')
print("#") #end=' ' the characters will be placed side by
size
#by default end='\n' '\n' means new line
G #
o #
o #
d #
#
E #
v #
e #
n #
i #
n #
g #
#method 2
m = "Dr Doom"
for i in range(0,len(m)):
print(m[i],end='')
#len(m) --> 7
Dr Doom
#method 3
m = "Robert Downey Junior"
p = len(m)
for i in range(-p,0):
print(m[i],end='')
Robert Downey Junior
#String operations
#String concatenation
s = 'Ms'
s1 = ' Marvel'
s2 = s + s1
print(s2)
Ms Marvel
#WAP to accept two numbers. Combine the two numbers to form a new
number.
m = int(input("Enter the first number: "))
n = int(input("Enter the second number: "))
a = str(m) + str(n) #str() function converts any input to string
print("The combined number",(a)) #int() function convert string
number to integer
Enter the first number: 25
Enter the second number: 35
The combined number 2535
#membership finds the presence or absence of a character in a string
m = "Good Night"
print('i' in m)
print('z' in m)
print('i' not in m)
print('z' not in m)
True
False
False
True
'''
ASCII or American Standard Code For Information Interchange
'A'-'Z' : 65 - 90
'a'-'z': 97 - 122
'0'-'9': 48 - 57
' '(blank space): 32
Suppose you want to find the ascii code of P
trick is 64 + count of the alphabet => 64 + 16(P) => 80
Suppose you want to find the ascii code of d
trick is 96 + count of the alphabet = > 96 + 4 => 100
'''
#WAP to accept a string. Display each character along with ascii
code
k = input("Enter a string: ")
for i in k:
print(i,ord(i))
#ord() means ordinal number. This function find the ascii code of
each character
Enter a string: Apple
A 65
p 112
p 112
l 108
e 101
#WAP to accept a number between 0 to 27. Display the alphabet
according to the order
k = int(input("Enter a number: "))
if 0<k<27: # k>0 and k<27
k=k+64
print("Letter is",chr(k))
else:
print("Number out of range")
#chr() function converts a ascii code to the appropriate character
Enter a number: 24
Letter is X
#WAP to accept a number. Split the digits of the numbers. Then
display the
#appropriate character according to the order the alphabet of the
digits
#INPUT: 378
#Output:
# 3 --> C
# 7 --> G
# 8 --> H
#Method 1
k = int(input("Enter a number: "))
while k>0:
d = k%10
print(d,"-->",chr(d+64))
k=k//10
Enter a number: 378
8 --> H
7 --> G
3 --> C
#Method 2
k = int(input("Enter a number: "))
k = str(k)
for i in k:
d = int(i)
print(d,"-->",chr(d+64))
Enter a number: 378
3 --> C
7 --> G
8 --> H
#String comparisions
print('A'<'a')
print('Mango'<'Jango') #false as J is smaller than M
print('Airplane'<'Aeroplane') #false as i is larger than e in terms
of ascii code
print('Airplane'>'Aeroplane') #true as e is smaller than i in terms
of ascii code
print("Apple" == "APPLE")
print("Apple" == "Apple")
print("Day" >= "day")
True
False
False
True
False
True
False
#String functions
k = input("Enter a sentence:")
print([Link]()) #this function checks a string is composed of
letters only or not
# space is not a letter that why it give you answer false
print([Link]()) #this function checks a string is composed of
integers only or not
print([Link]()) #this function checks a string is composed of
letters or digits or both
print([Link]()) #this function check a string is smaller letter
or not
print([Link]()) #this function checks a string is uppercase
letters or not
Enter a sentence: ABC
True
False
True
False
True
#More functions
k = input("Enter a string: ")
print([Link]()) #converts entire string to smaller letters
print([Link]()) #converts entire string to capital letters
print([Link]()) #converts the string to sentence, meaning
word's first alphabet will in captal letter
print([Link]()) #converts the string to sentence, converts each
word's first alphabet to capital letter
print([Link]()) #each alphabet will be converted to small and
capital interchangebly
Enter a string: Hail Hitler
hail hitler
HAIL HITLER
Hail hitler
Hail Hitler
hAIL hITLER
#replace(old,new)
k="Blue Bag Blue Ball"
print([Link]("Blue","Red"))
Red Bag Red Ball
# isspace() function check a character is space or not
k = " "
print([Link]())
k = 'Jai Hitler'
print([Link]())
True
False
#find() function find the index of a string only the first
chracter's index
# if the string is not present then it returns -1
k = "The Quick Brown Fox Jumps Over The Lazy Dog"
s = [Link]("Oil")
print(s)
s = [Link]("Over")
print(s)
k = "Kratos the victor of the Olympus"
print([Link]("the",9,len(k)))
-1
26
21
#count() counts the repetition of a given string in sentence
k = "The Quick Brown Fox Jumps Over The Lazy Dog"
p = [Link]("The")
print(p)
#WAP to accept a string. Find the frequency of each alpahbet
#Input: Apple
# A -> 1
# p -> 2
# l -> 1
# e -> 1
n = input("Enter a string: ")
for i in range(65,91):
c=0 #counter
for j in n:
m = [Link]()
k = chr(i)
if k==m:
c=c+1
if c!=0:
print("Frequency of",chr(i),"is",c)
Enter a string: Apple
Frequency of A is 1
Frequency of E is 1
Frequency of L is 1
Frequency of P is 2
#index() finds the first occurrence of the a given string in a
sentence and display the index
# similar to find the function
s = "The Quick Brown Fox Jumps Over The Lazy Dog"
print([Link]("The"))
#split() function breaks a sentence in list of words
#syntax: <string>.split(<separator>,<maxsplit>)
#seperator: is defines any delimeter example whitespace means space,
comman, semicolon etc (by default
# whitespace is separator
#maxsplit: It defines the number of splits (optional).
s = "Jack and Jill went up the hill"
print([Link]())
s="Good@Morning@India@2050"
print([Link]("@",2))
# means the first two delimeters will be considered for splitting
and rest will not be considered
['Jack', 'and', 'Jill', 'went', 'up', 'the', 'hill']
['Good', 'Morning', 'India@2050']
#partition function breaks a sentence into multiple parts
#the partition value will always be at the center of partition of a
sentence
#partition breaks a string into three elements in a tuple
m = "Jack and Jill went up the hill"
print([Link]("and"))
#in partition() if a string is not present then
# the first element will be the whole string
# second and third element will be empty string
print([Link]("green"))
('Jack ', 'and', ' Jill went up the hill')
('Jack and Jill went up the hill', '', '')
#strip() function is used to remove the leading and preceding
whitespace(by default)
#if a character is mentioned it is removed from left and right if
the string
s = " Good Evening "
print([Link]())
s="-------Good-Evening-----"
print([Link]("-")) #the dashes before and after the sentence.
Good Evening
ood-Evenin
#lstrip() function removes the whitespaces from the left hand side
#if a character is mentioned that is removed from the left side
s="***Good-Evening$$$$"
print([Link]("*"))
#rstrip() function removes the whitespaces from the right hand side
#if a character is mentioned that is removed from the right side
print([Link]('$'))
Good-Evening$$$$
***Good-Evening
#startswith() function check a string is present at the beginning of
string or not
z = "Python is a high level language"
print([Link]("Python"))
#endswith() function check a string is present at the end of string
or not
print([Link]("uage"))
True
True
#join() function creates a new string by concatenating the elements
z = ['All','is','well']
k = " ".join(z)
print(k)
All is well
#To join multiple string
w = "Hello"
w2 = "world"
k = " ".join([w,w2])
print(k)
Hello world