PYTHON ASSIGNMENT 7 – STRING
HEMANTH RAJ S (CIVIL)
Problem solving in python, S01
2310064
1. Write a function called rotate_word that takes a string and an integer as Parameters, and returns
a new string that contains the letters from the original String rotated by the given amount.
CODING:
Def rotate_word(text, shift):
Result = ‘’
For char in text:
If char.isalpha():
Shifted = ord(char) + shift
If char.islower():
If shifted > ord(‘z’):
Shifted -= 26
Elif shifted < ord(‘a’):
Shifted += 26
Elif char.isupper():
If shifted > ord(‘Z’):
Shifted -= 26
Elif shifted < ord(‘A’):
Shifted += 26
Result += chr(shifted)
Else:
Result += char
Return result
# Test the function
Sample_input = “RIVER IBM”
Key = 3 # Shift for RIVER
Key2 = -1 # Shift for IBM
Output = rotate_word(sample_input, key)
Output2 = rotate_word(output, key2)
Print(output2) # Output: “EVIRE HAL”
2. Write a Python program to convert a given string to Snake case. (Hint: use Join()] Snake case is a
variable naming convention where each word is in lower case, and Separated by underscores.
Snake_case refers to the style of writing in which each space is Replaced by an underscore (_)
character, and all letters of each word written in lowercase. It is a commonly used naming
convention in computing, for example for variable and Subroutine names, and for filenames.
Ignore special characters anywhere in the string, And numbers in the beginning of the string.
For example: Date of Birth → date_of_birth This Is In Camel Case → this_is_in_camel_case
123Foo Bar → foo_bar Foo3@ Bar# 23 → foo3_bar_23
CODING:
Import re
Def to_snake_case(input_string)
Cleaned_string = re.sub(r’[^a-zA-Z0-9\s]’, ‘’, input_string)
Words = cleaned_string.split()
Snake_case = ‘_’.join(word.lower() for word in words)
Return snake_case
ample usage:
Input_string = “Date of Birth”
Snake_case_output = to_snake_case(input_string)
Print(snake_case_output)
3. Write a program in python that accepts a string to set up passwords. The program should check
the validity of the password.
CODING:
Import re
Def check_password_validity(password):
# Check length
If len(password) < 8:
Return False
# Check for uppercase, lowercase, digit, and special character
If not re.search(r”[A-Z]”, password):
Return False
If not re.search(r”[a-z]”, password):
Return False
If not re.search(r”\d”, password):
Return False
If not re.search(r”[@#$%&*+\-=?_]”, password):
Return False
Return True
# Taking user input
User_password = input(“Enter a password: “)
If check_password_validity(user_password):
Print(“Valid password!”)
Else:
Print(“Invalid password!”)
ADDITIONAL QUESTIONS :
1. Check whether a string is a palindrome or not.
Example: By reversing each letter of REDIVIDER → REDIVIDER Detartrated – an 11-letter word that
the Guinness Book of World Records says is the Longest English palindrome
CODING:
Def is_palindrome(s):
# Remove non-alphanumeric characters and convert to lowercase
S = ‘’.join(e.lower() for e in s if e.isalnum())
Return s == s[::-1]
2. Read two strings and find the longest common prefix.
Example: Flower, floor -> fl Pot, plot -> p Hot, pot -> no common prefix
CODING:
Def longest_common_prefix(str1, str2):
Prefix = “”
Min_len = min(len(str1), len(str2))
For I in range(min_len):
If str1[i] == str2[i]:
Prefix += str1[i]
Else:
Break
Return prefix if prefix else “No common prefix”
# Example usage:
Result = longest_common_prefix(“flower”, “floor”)
Print(result) # Output: “fl”
Result = longest_common_prefix(“pot”, “plot”)
Print(result) # Output: “p”
Result = longest_common_prefix(“hot”, “pot”)
Print(result) # Output: “No common prefix”
3. Count number of vowels, consonants and white spaces in the string.
CODING:
Def count_chars(string):
Vowels = 0
Consonants = 0
Spaces = 0
# Converting the string to lowercase to handle both uppercase and lowercase characters
String = string.lower()
For char in string:
If char in ‘aeiou’:
Vowels += 1
Elif char.isalpha():
Consonants += 1
Elif char.isspace():
Spaces += 1
Return vowels, consonants, spaces
# Example usage:
Input_string = “This is an example string.”
Vowels_count, consonants_count, spaces_count = count_chars(input_string)
Print(f”Vowels: {vowels_count}”)
Print(f”Consonants: {consonants_count}”)
Print(f”Spaces: {spaces_count}”)
4. Write a menu driven program using inbuilt functions to perform the following:
CODING:
Def substring_occurrence():
String = input(“Enter the string: “)
Substring = input(“Enter the substring to find: “)
Count = string.count(substring)
Print(f”The substring ‘{substring}’ occurs {count} times in the string ‘{string}’.”)
Def last_occurrence_from_end():
String = input(“Enter the string: “)
Substring = input(“Enter the substring to find from the end: “)
Last_index = string.rfind(substring)
If last_index != -1:
Print(f”The last occurrence of ‘{substring}’ from the end is at index {last_index}.”)
Else:
Print(f”The substring ‘{substring}’ is not found in the string ‘{string}’ from the end.”)
Def right_justify_string():
String = input(“Enter the string to right justify: “)
Width = int(input(“Enter the width for justification: “))
Justified_string = string.rjust(width)
Print(f”The right justified string is: ‘{justified_string}’”)
Def capitalize_first_letter():
String = input(“Enter the string to capitalize: “)
Capitalized_string = string.capitalize()
Print(f”The string with the first letter capitalized: ‘{capitalized_string}’”)
Def check_alphanumeric():
String = input(“Enter the string to check if alphanumeric: “)
If string.isalnum():
Print(f”The string ‘{string}’ is alphanumeric.”)
Else:
Print(f”The string ‘{string}’ is not entirely alphanumeric.”)
# Menu
While True:
Print(“\nMenu:”)
Print(“1. Occurrence of a substring”)
Print(“2. First occurrence of a substring from the end”)
Print(“3. Right justify a string”)
Print(“4. Capitalize the first letter of a string”)
Print(“5. Check whether the string is alphanumeric”)
Print(“6. Exit”)
Choice = input(“Enter your choice (1-6): “)
If choice == ‘1’:
Substring_occurrence()
Elif choice == ‘2’:
Last_occurrence_from_end()
Elif choice == ‘3’:
Right_justify_string()
Elif choice == ‘4’:
Capitalize_first_letter()
Elif choice == ‘5’:
Check_alphanumeric()
Elif choice == ‘6’:
Print(“Exiting the program. Goodbye!”)
Break
Else:
Print(“Invalid choice. Please enter a number between 1 and 6.”)