# Solution Exercise 58: python algorithm which replace all prentheses by brackets within given text

#### Exercise 58

Write a Python algorithm as a function which takes a string s as input and which returns another string obtained from s by replacing the possibly existing parentheses '(' and ')' in the string s with square brackets '[' and ']' without using the replace() method. 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 replace_parentheses(s):
result = ''
for c in s:
if c == '(':
result += '['
elif c == ')':
result += ']'
else:
result += c
return result

s = "Python (created by Guido van Rossam) is oriented programming language (oop)."
result = replace_parentheses(s)
print(result)  # Output: "Python [created by Guido van Rossam] is oriented programming language [oop]."```

In this algorithm:
We iterate over every character in the input string s: using a for loop.
Then we build a new string result: by appending characters to it one by one.
If we encounter an opening parenthesis '(': we append a square bracket '[' instead. If we encounter a closing parenthesis ')', we append a square bracket ']' instead.
For all other characters: we just append them as-is.

#### Note

The output of this replace_parentheses() function is the same as that of the replace() method.

Younes Derfoufi
my-courses.net