Python-courses-python-exercises-python-Array, String, user Inputs packages

Exercise 58

Write a Python program as a function which takes as parameter a string s and which returns another string obtained from s by replacing the possibly existing parentheses '(' and ')' in the string s with square brackets '[' and ']'. Example if s = "Python (created by Guido van Rossam) is oriented programming language (oop)." The function must returns: "Python [created by Guido van Rossam] is oriented programming language [oop]"

Solution

def transform(s):

# initializing the transformed string
transformed = ""

for x in s:
if x == '(':
transformed = transformed + '['
elif x == ')':
transformed = transformed + ']'
else:
transformed = transformed + x
return transformed

s = "Python (created by Guido van Rossam) is oriented programming language (oop)."

print(transform(s))
# The output is : Python [created by Guido van Rossam] is oriented programming language [oop].

Younes Derfoufi
my-courses.net

Leave a Reply