String Operators
Ques: Write a program to input an integer and check if it contains any 0 in it ?
n = int(input('Enter a number: '))
s = str (n)
if '0' in s :
print("there's a 0 in",n)
else:
print('No 0 in',n)
Ques: An easy way to print a blank line is print(). However, to print ten blank lines, would you write print() 10 times ? Or is there a smart alternative ? If yes, write code to print a line with 30 '=' characters ?
print('='*30)
print('\n'*9)
print('='*30)
Ques: Write a program that asks a user for a user-name and a code.Ensure that the user does not use their username as part of their code ?
uname = input('Enter user name: ')
code = input('Enter code: ')
if uname in code:
print('Your code should not contain your user name.')
print("Thank You")
Ques: Make sure that pcode does not contain username and matches Trident111' ?
uname = input('Enter user name: ')
pcode = input('Enter code: ')
if uname not in pcode and pcode=='Trident111':
print('Your code is Valid to proceed.')
else:
print('Your code is Not Valid.')
Ques: Program that prints the following pattern wthout using any nested loop:
#
##
###
####
#####
string = '#'
pattern = ""
for a in range(5):
pattern += string
print(pattern)
Traversing a String
Ques: Program to read a string and display it in reverse order-display one character per
line. Do not create a reverse string, just display in reverse order ?
string1 = input('Enter a string: ')
print('The',string1,'in reverse order is: ')
length = len(string1)
for a in range (-1,-length-1,-1):
print(string1[a],end="")
Ques: Program to read a string and display it in the form:
first character last character
second character second last character
... ... ?
string1 = input('Enter a string: ')
length = len(string1)
i = 0
for a in range (-1,-length-1,-1):
print(string1[i],'\t', string1[a])
i+=1
String Slicing
Ques: Write a program to input two strings if string1 is contained in string2, then create a third string with the first four characters of string2, added with the word “Restore”?
s1 = input('Enter String 1: ')
s2 = input('Enter String 2: ')
print('Original string: ',s1,s2)
if s1 in s2:
s3 = s2[0:4]+'Restore'
print('Final String: ',s1,s3)
else :
print('Final String: ',s1,s2)
Ques: Write a program to input a string and check if it is a palindrome string using a string slice ?
s= input ("Enter a String: ")
if s==s[::-1] :
print(s,"is a Palindrome.")
else:
print(s,"is not a Palindrome.")
String Function and Methods
Ques:Program that reads a line and prints its statistics like : ?
line = input('Enter a line: ')
lowercount = uppercount = 0
digitcount= alphacount = symcount = 0
for a in line:
if a.islower():
lowercount += 1
elif a.isupper():
uppercount += 1
elif a.isdigit():
digitcount += 1
elif a.isalnum() != True and a != ' ':
symcount += 1
print("Number of uppercase letter: ", uppercount)
print("Number of lowercase letter: ", lowercount)
print("Number of alphabets: ", uppercount+lowercount)
print("Number of digits: ", digitcount)
print("Number of symbols: ", symcount)
Ques: Program that reads a line and a substring. It should then display the number of occurrences of the given substring in the line ?
line = input ( "Enter line :" )
sub = input( "Enter substring :" )
length = len(line)
lensub = len(sub)
start = count = 0
end = length
while True :
pos = line.find(sub, start, end)
if pos != -1 :
count += 1
start = pos + lensub
else :
break
if start >= length :
break
print ("No. of occurrences of",sub,":",count)
Ques: Write a program that inputs a stning that contains a decimal number and prints out the decimal part of the number. For instance,If 515.8059 is given,the program should print out 8059 ?
s =input("Enter a string (a decimal nmuber ): ")
t = s.partition( '.')
print("Given string:", s)
print("part after decimal", t[2])
Ques: Write a program that inputs individual words of your school motto and joins them to make a string. It should also input the day, month and year of your school's foundation date and print the complete date ?
print( "Enter words of your school motto, one by one")
w1 = input ("Enter word 1: ")
w2 = input("Enter word 2: " )
w3 = input( "Enter word 3: ")
w4 = input("Enter word 4: ")
motto=" ".join( [w1, w2, w3,w4 ] )
print( "Enter your school's foundation date: ")
dd = input("Enter dd: ")
mm = input("Enter mm: ")
YYYY = input("Enter yyyy: ")
dt = "/".join( [dd, mm, YYYY])
print("School motto : " , motto)
print("School foundation date: ", dt)
Ncert Solutions
Ques: Write a program to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised) ?
s = input("Enter a string : ")
print ( "String With Title Case is : ", s.title( ))
Ques: Write a program which takes two inputs one is a string and other is a character. The function should create a new string after deleting all occurrences of the character from the siring and return the new string ?
s = input ("Enter a string :")
c = input ("Enter a character :")
print( "String With deleted characters is: ")
print(s.replace(c,''))
Ques: Input a string having some digits. Write a program to calculate the sum of digits present in this String ?
s = input ("Enter a string : ")
dsum = 0
for a in s:
if a.isdigit():
dsum += int(a)
print( "Sum of string's digits is ",dsum)
Ques: Write a program that takes a sentence as an input where each word in the sentence is separated by a space. The function should replace each blank with a hyphen and then print the modified sentence ?
s = input ("Enter a string :")
print ("Replaced 5tr i ng is:")
print (s. replace('','-'))
Practice Problems
Ques: Write a program that takes a string with multiple words and then capitalizes the first letter of each word and forms a new string out of it ?
string = input ( "Enter a string : ")
length = len(string)
a=0
end= length
string2 = '' #empty string
while a < length :
if a== 0 :
string2 += string[0]. upper()
a+- 1
elif (string[a] =='' and string[a+1] !='') :
string2 += string[a]
string2 += string[a+1]. upper()
a += 2
else:
string2 += string[a]
a += 1
print("Original String : ",string)
print("Capitalized word String",string2)
Ques: Write a program that reads a string and checks whether it is a palindrome string or not without using string slice ?
string = input ( "Enter a string : ")
length = len(string)
mid = length//2
rev = -1
for a in range(mid):
if string[a] == string[rev] :
a += 1
rev -= 1
print (string, "is a palindrome")
break
else:
print (string, "is not a palindrome")
break
Ques: Write a program that reads a string and display the longest substring of the given string having just the consonants ?
string = input( "Enter a string : ")
length= len(string)
print(length)
maxlength = 0
maxsub = ''
sub=''
lensub = 0
for a in range(length):
if string[a] in 'aeiou' or string[a] in 'AEIOU':
if lensub > maxlength :
maxsub = sub
maxlength = lensub
sub=''
lensub = 0
else:
sub += string[a]
lensub = len(sub)
print("Maximum length consonant substring is : ", maxsub, end=" ")
print('with', maxlength,'characters' )
Ques: Write a program that reads n string and then prints a string that capitalizes every other letter in the string eg-> passion becomes pAsSiOn ?
string = input( "Enter a string :" )
length = len (string)
print ("Original string :", string)
string2 = " " # empty string
for a in range(0, length, 2):
string2 += string[a]
if a< (length-1) :
string2 += string[a + 1].upper()
print ("Alternatively capitalized string :" , string2)
Ques: Write a program that reads email-id of persons in the form of a string and ensures that it belongs to domain @coderzunited.com. (Assumption : No invalid characters are there in email-id) ?
email = input( "Enter your email id : " )
domain = '@coderzunited.com'
ledo = len(domain)
lema = len(email)
sub= email[lema-ledo : ]
if sub == domain :
if ledo != lema :
print ("It is valid email id")
else:
print ("This is invalid email ld- contains just the domain name.")
else:
print('This email-id is either not valid or belongs to some other domain')
Ques: Write a program that asks the user for a string s and a character c; and then it prints out the location of each character c in the string s ?
s = input('Enter some text: ')
c = input( 'Enter a character: ')
print("In", s, "character", c, "found at these locations: ",end="")
for i in range( len(s) ):
if s[i] == c:
print(i, end=",")
Ques: Write a program that asks the user for a string and creates a new string that doubles each character of the original string. For instance, if the user enters Coderz*United, the output should be CCooddeerrzz**UUnniitteedd ?
s = input('Enter a string : ')
ds = ""
for c in s :
ds = ds + c*2
print("Originalstring:",s)
print("Doubled string:", ds)
Ques: Write a program that inputs a line of text and prints its each word in a separate line. Also, print the count of words in the line ?
s = input("Enter a line of text :")
count = 0
for word in s.split():
print( word )
count += 1
print("Total words : ", count)
Ques: Write a program to input a string and check if it contains a digit or not ?
strg = input( "Enter a string :")
test = False
dig = "0123456789"
for ch in strg:
if ch in dig:
print("The string contains a digit.a")
test= True
break
if test == False:
print("The string doesn't contain a digit.")
Ques: Write a program to input an address containing a pincode and extract and print the pincode from the input address ?
add = input("Enter text:")
i = 0
ln= len(add)
while i < ln:
ch = add[i]
if ch.isdigit():
sub = add[i:(i+6)]
if sub.isdigit ():
print(sub)
break
i += 1
Ques: Write a program that takes a string with multiple words and then capitalizes the first letter of each word and forms a new string out of it ?
string = input ( "Enter a string : ")
length = len(string)
a=0
end= length
string2 = '' #empty string
while a < length :
if a== 0 :
string2 += string[0]. upper()
a+- 1
elif (string[a] =='' and string[a+1] !='') :
string2 += string[a]
string2 += string[a+1]. upper()
a += 2
else:
string2 += string[a]
a += 1
print("Original String : ",string)
print("Capitalized word String",string2)
Ques: Write a program that reads a string and checks whether it is a palindrome string or not without using string slice ?
string = input ( "Enter a string : ")
length = len(string)
mid = length//2
rev = -1
for a in range(mid):
if string[a] == string[rev] :
a += 1
rev -= 1
print (string, "is a palindrome")
break
else:
print (string, "is not a palindrome")
break
Ques: Write a program that reads a string and display the longest substring of the given string having just the consonants ?
string = input( "Enter a string : ")
length= len(string)
print(length)
maxlength = 0
maxsub = ''
sub=''
lensub = 0
for a in range(length):
if string[a] in 'aeiou' or string[a] in 'AEIOU':
if lensub > maxlength :
maxsub = sub
maxlength = lensub
sub=''
lensub = 0
else:
sub += string[a]
lensub = len(sub)
print("Maximum length consonant substring is : ", maxsub, end=" ")
print('with', maxlength,'characters' )
Ques: Write a program that reads n string and then prints a string that capitalizes every other letter in the string eg-> passion becomes pAsSiOn ?
string = input( "Enter a string :" )
length = len (string)
print ("Original string :", string)
string2 = " " # empty string
for a in range(0, length, 2):
string2 += string[a]
if a< (length-1) :
string2 += string[a + 1].upper()
print ("Alternatively capitalized string :" , string2)
Ques: Write a program that reads email-id of persons in the form of a string and ensures that it belongs to domain @coderzunited.com. (Assumption : No invalid characters are there in email-id) ?
email = input( "Enter your email id : " )
domain = '@coderzunited.com'
ledo = len(domain)
lema = len(email)
sub= email[lema-ledo : ]
if sub == domain :
if ledo != lema :
print ("It is valid email id")
else:
print ("This is invalid email ld- contains just the domain name.")
else:
print('This email-id is either not valid or belongs to some other domain')
Ques: Write a program that asks the user for a string s and a character c; and then it prints out the location of each character c in the string s ?
s = input('Enter some text: ')
c = input( 'Enter a character: ')
print("In", s, "character", c, "found at these locations: ",end="")
for i in range( len(s) ):
if s[i] == c:
print(i, end=",")
Ques: Write a program that asks the user for a string and creates a new string that doubles each character of the original string. For instance, if the user enters Coderz*United, the output should be CCooddeerrzz**UUnniitteedd ?
s = input('Enter a string : ')
ds = ""
for c in s :
ds = ds + c*2
print("Originalstring:",s)
print("Doubled string:", ds)
Ques: Write a program that inputs a line of text and prints its each word in a separate line. Also, print the count of words in the line ?
s = input("Enter a line of text :")
count = 0
for word in s.split():
print( word )
count += 1
print("Total words : ", count)
Ques: Write a program to input a string and check if it contains a digit or not ?
strg = input( "Enter a string :")
test = False
dig = "0123456789"
for ch in strg:
if ch in dig:
print("The string contains a digit.a")
test= True
break
if test == False:
print("The string doesn't contain a digit.")
Ques: Write a program to input an address containing a pincode and extract and print the pincode from the input address ?
add = input("Enter text:")
i = 0
ln= len(add)
while i < ln:
ch = add[i]
if ch.isdigit():
sub = add[i:(i+6)]
if sub.isdigit ():
print(sub)
break
i += 1