0% found this document useful (0 votes)
237 views

Module 6 Regular Expressions Assignment

This document contains two Python programming assignments involving regular expressions. The first assignment checks if a string contains only allowed characters like letters and numbers. The second replaces spaces, commas and dots in a string with colons.

Uploaded by

Gïrìsh Gowrí
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views

Module 6 Regular Expressions Assignment

This document contains two Python programming assignments involving regular expressions. The first assignment checks if a string contains only allowed characters like letters and numbers. The second replaces spaces, commas and dots in a string with colons.

Uploaded by

Gïrìsh Gowrí
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

MODULE – 6 ASSIGNMENTS

Regular Expression

1) Write a Python program to check that a string contains only a certain set of characters.
(In this case a-z, A-Z, and 0-9).

import re

def contains_only_allowed_characters(input_string):
# Define a regular expression pattern to match the allowed characters
pattern = r'^[a-zA-Z0-9]+$'

# Use re.match() to check if the entire string matches the pattern


if re.match(pattern, input_string):
return True
else:
return False

# Test cases
input_string1 = "Hello123"
input_string2 = "Hello@123"

if contains_only_allowed_characters(input_string1):
print(f"'{input_string1}' contains only allowed characters.")
else:
print(f"'{input_string1}' contains disallowed characters.")

if contains_only_allowed_characters(input_string2):
print(f"'{input_string2}' contains only allowed characters.")
else:
print(f"'{input_string2}' contains disallowed characters.")

2) Write a Python program to replace all occurrences of space, commas, or dots with a
colon.

def replace_spaces_commas_dots_with_colon(input_string):
# Replace spaces, commas, and dots with a colon using the replace() method
modified_string = input_string.replace(' ', ':').replace(',', ':').replace('.', ':')
return modified_string

# Test case
original_string = "This is, a test. String with, spaces and.dots."
modified_string = replace_spaces_commas_dots_with_colon(original_string)
print("Original String:", original_string)
print("Modified String:", modified_string)

You might also like