30.Example Programs using Strings

Remove all vowel characters from a string( university question)
vowels="AEIOUaeiou"
s=input("Enter the string...")
ns=""
for char in s:
    if char not in vowels:
        ns=ns+char
print("new string after removing vowels=",ns)

Remove characters at odd index positions from a string ( university question)
s=input("Enter the string..:")
i=0
ns=""
while i<len(s):
    if i%2==0:
        ns=ns+s[i]
    i=i+1
print("New string:",ns)

palindrome checking without reversing the string ( university question)
s=input("Enter the string...")
if s==s[::-1]:
    print("palindrome..")
else:
    print("not palindrome...")

Palindrome checking using loop
s=input("Enter the string..")
beg=0
end=len(s)-1
while beg<end:
   if s[beg]!=s[end]:
         print("Not palindrome")
         break
   beg+=1
   end-=1
else:
  print("Palindrome")

Replace all the spaces in the input string with * or if no spaces found,put $ at the start and end of the string.(university question)
s=input("Enter the string:")
s=s.replace(" ","*")
if "*" not in s:
    s="\$"+ s +"\$"
    print(s)
else:
    print(s)

Slice the string to two separate strings; one with all the characters in the odd indices and one with all characters in even indices.(university question)
s=input("enter the string:")
eps=s[0:len(s):2]
print("slice with even position characters:",eps)
ops=s[1:len(s):2]
print("slice with odd position chracters:",ops)

Binary to Decimal conversion
bitstring=input("Enter a binary number...")
decno=0
expnt=len(bitstring)-1
for bit in bitstring:
    decno=decno+int(bit)* 2 ** expnt
    expnt=expnt-1
print ("The decimal number is=", decno)

Decimal to Binary Conversion
decno=int(input("Enter the decimal number...."))
if decno==0:
    print("The binary equivalent is....0000")
else:
    binaryno=""
    while decno!=0:
        b=decno%2
        binaryno=str(b)+binaryno
        decno=decno//2
    print("The binary equivalent is....",binaryno)

Remove all occurrence of a substring from a string
s=input("enter the string..")
ss=input("enter substring to remove..")
ls=len(s) # length of the string
lss=len(ss) # length of the substring
ns="" # new string
i=0
while i<ls:
  css=s[i:lss+i] #css is the substring to be compared extracted from main string
  if css==ss:
    i=i+lss
  else:
    ns=ns+s[i]
    i=i+1
print("new string",ns)
The above program can also be written with built in function replace()
str=input("Enter string ..")
sstr=input("Enter the substring to remove..")
nstr=str.replace(sstr,"")
print("string after removing substring..",nstr)

Converting all lowercase letters into uppercase ( university question)
import string
s=input('Enter the string...')
ns=""
for c in s:
 if c in string.ascii_lowercase:
    c=chr(ord(c)-32)
 ns=ns+c
print("new string=",ns)

Swapping case ..small letters to capital letters and capital letters to small letters.
s=input('Enter the string...')
ns=""
sletter='abcdefghijklmnopqrstuvwxyz'
cletter='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for c in s:
  if c in sletter:
     c=chr(ord(c)-32)
  elif c in cletter:
    c=chr(ord(c)+32)
  ns=ns+c
print("new string=",ns)

Program to replace all occurrence of a substring with a new substring (university question)
s=input("enter string..")
ss=input("enter substring to remove..")
nss=input("enter the substring to replace....")
ls=len(s)
lss=len(ss)
ns=""
i=0
while i<ls:
  css=s[i:lss+i]
  if css==ss:
     ns=ns+nss
     i=i+lss
  else:
     ns=ns+s[i]
     i=i+1
print("new string",ns)

Reversing the first and second half of a string separately ( university question)
s=input("Enter the string..:")
l=len(s)
fs=s[0:l//2]
ss=s[l//2:]
fs=fs[::-1]
ss=ss[::-1]
s=fs+ss
print("New string after reversal:::",s)

Encrypt a string using the shift cipher( key=3 Ceaser cipher)
import string
plaintxt=input("enter plain text in small letters..")
k=int(input("Enter the key...."))
s=string.ascii_lowercase
ciphertxt=""
for c in plaintxt:
    i=s.find(c)
    if i!=-1:
        ni=(i+k) % 26
        ciphertxt=ciphertxt+s[ni]
    else:
        ciphertxt=ciphertxt+c
print("cipher text...",ciphertxt)

Write a Python program to check the validity of a password given by the
user.
The Password should satisfy the following criteria:
1. Contains at least one letter between a and z
2. Contains at least one number between 0 and 9
3. Contains at least one letter between A and Z
4. Contains at least one special character from $, #, @
Minimum length of password: 6
import getpass
dig='0123456789'
cl="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sl="abcdefghijklmnopqrstuvwxyz"
sc="$#@"
flag1=0;flag2=0;flag3=0;flag4=0;flag5=0
password=getpass.getpass()
if len(password)>=6:
    flag5=1
for c in password:
        if c in dig:
            flag2=1
        if c in sl:
            flag1=1
        if c in cl:
            flag3=1
        if c in sc:
            flag4=1
if flag1 and flag2 and flag3 and flag4 and flag5:
    print("Strong password")
else:
    print("Invalid password")
  
Write Python program to count the total number of vowels, consonants, digits and blanks in a string.(university question)
s = input('Enter the string:')
s = s.lower()
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
digits = "1234567890"
space = " "
c = 0
v = 0
d = 0
ws = 0
for i in s:
    if i in vowels:
        v+=1
    elif i in consonants:
        c+=1
    elif i in digits:
        d+=1
    elif i in space:
        ws+=1
print("Consonents={},Vowels={},Digits={},Spaces={}".format(c,v,d,ws))
Note: you can do this program using library functions
Count number of letters , digits, words,uppercase and lower case letters in a string
num_letters = 0
num_digits = 0
num_words = 0
num_uppercase = 0
num_lowercase = 0
input_string = input("Enter a string: ")

for char in input_string:
    if char.isalpha():
        num_letters += 1
    if char.islower():
        num_lowercase += 1
    elif char.isupper():
         num_uppercase += 1
    elif char.isdigit():
        num_digits += 1

# Count words
words = input_string.split()
num_words = len(words)
    
print("Number of letters:", num_letters)
print("Number of digits:", num_digits)
print("Number of words:", num_words)
print("Number of uppercase letters:",num_uppercase)
print("Number of lowercase letters:",num_lowercase)

Assume that the variable data refers to the string "Python rules!". Use a string method to perform the following tasks: ( University Question)
a. Obtain a list of the words in the string.
b. Convert the string to uppercase.
c. Locate the position of the string "rules" .
d. Replace the exclamation point with a question mark.

data="Python rules!"

words=data.split(" ")
for w in words:
    print(w)
    
data=data.upper()
print(data)

pos=data.index('rules')
print(pos)

data=data.replace('!','?')
print(data)
Write a Python program to get a string and change all occurrences of its first character to '$', except the first character itself.(university question)
Example:onion  will change to oni$n.

def change_first_char_occurrences(input_string):
    # Check if the string is not empty
    if input_string:
        first_char = input_string[0]

        # Replace all occurrences of the first character (excluding the first one) with '$'
        modified_string = first_char + input_string[1:].replace(first_char, '$')

        return modified_string

    return input_string  # Return the original string if it's empty

# Get input from the user
user_input = input("Enter a string: ")

# Call the function and print the result
result = change_first_char_occurrences(user_input)
print("Modified string:", result)

Output:
Enter a string: onion
Modified string: oni$n

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators