Sponsor

Python Assignment 2 Basic Programming in Python | Python Tutorial For Beginners | Learn Python With SoftwareTechIT

Assignment 2



SET A ]

1. Write a Python program to count the number of characters (character frequency) in a string.

Sample String : google.com'

Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}

Ans=

from collections import Counter
str=input("Enter string :")
c=Counter(str)
print(c)


2. Write a Python program to get a string made of the first 2 and the last 2 chars

from a given a string. If the string length is less than 2, return instead of the empty string.

Sample String : 'General12'

Expected Result : 'Ge12'

Sample String : 'Ka'

Expected Result : 'KaKa'

Sample String : ' K'

Expected Result : Empty String

Ans=


str=input("enter string :")
if(len(str)<2):
    print("empty string")
elif(len(str)==2):
    print(str+str)
else:
    f1=str[:2]+str[-2:]
    print(f1)


3. Write a Python program to get a string from a given string where all

occurrences of its first char have been changed to '$', except the first char itself.

 Sample String :

'restart'

Expected Result : 'resta$t'

Ans=

str=input("enter string ")
fir=str[0]
#replace first character with symbol
print(fir+str[1:].replace(fir,'$'))

4.Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.

Sample String : 'abc', 'xyz'

Expected Result : 'xycabz'

Ans=

first=input("enter
first string")
sec=input("enter second string")
s=sec[:2]
f=first[:2]

print(s+first[2:]+f+sec[2:])

SET B ]

1. Write a Python program to change a given string to a new string where the first and last chars have been exchanged.

Ans=

str=input("enter
string :")
firstchar=str[0]
lastchar=str[-1]
midcharstr=str[1:-1]

print(lastchar+midcharstr+firstchar)

2. Write a Python program to remove the characters which have odd index values of a given string.

Ans=

str=input("enter String :")
for i in range(len(str)):
    if i%2==0:
        print("".join(str[i]))

3. Write a Python program to count the occurrences of each word in a given sentence.

Ans=

from collections
import Counter
sentense=input("enter sentense :")
ad=sentense.split()
a=Counter(ad)

print(a)

4. Write a python program to count repeated characters in a string.

Sample string: 'thequickbrownfoxjumpsoverthelazydog'

Expected output :

o 4

e 3

u 2

h 2

r 2

t 2

Ans=

from collections
import Counter
str=input("enter String :")
fre=Counter(str)
for key,value in fre.items():
    if value>1:

        print(key,"=",value)



More Popular Posts:- 

Post a Comment

0 Comments