151k views
2 votes
#Write a function called "in_parentheses" that accepts a

#single argument, a string representing a sentence that
#contains some words in parentheses. Your function should
#return the contents of the parentheses.
#
#For example:
#
# in_parentheses("This is a sentence (words!)") -> "words!"
#
#If no text appears in parentheses, return an empty string.
#Note that there are several edge cases introduced by this:
#all of the following function calls would return an empty
#string:
#
# in_parentheses("No parentheses")
# in_parentheses("Open ( only")
# in_parentheses("Closed ) only")
# in_parentheses("Closed ) before ( open")
#
#You may assume, however, that there will not be multiple
#open or closed parentheses.
#Write your function here!
def in_parentheses(a_string):
import re
regex = re.compile(".*?\((.*?)\)")
result = re.findall(regex, a_string)
return(result)
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print (including the blank lines):
#words!
#
#as he is doing right now
#
#
#!
print(in_parentheses("This is a sentence (words!)."))
print(in_parentheses("No parentheses here!"))
print(in_parentheses("David tends to use parentheses a lot (as he is doing right now). It tends to be quite annoying."))
print(in_parentheses("Open ( only"))
print(in_parentheses("Closed ) only"))
print(in_parentheses("Closed ) before ( open"))
print(in_parentheses("That's a lot of test cases(!)"))

User Dontay
by
5.7k points

2 Answers

6 votes

Answer:

import regex as re

def in_parentheses(a_string):

regeX = re.compile(".*?\((.*?)\)")

result = re.findall(regeX, a_string)

return str(result).replace("[","").replace("]","")

print("test 1: "+in_parentheses("Open ( only"))

print("test 2: "+in_parentheses("This is a sentence (words!)."))

#Write a function called "in_parentheses" that accepts a #single argument-example-1
User Eli Gassert
by
5.2k points
1 vote

Here's an implementation of the in_parentheses function in Python:

The Code

import re

def in_parentheses(a_string):

result = re.search(r'\((.*?)\)', a_string)

return result.group(1) if result else ""

# Test cases

print(in_parentheses("This is a sentence (words!)."))

print(in_parentheses("No parentheses here!"))

print(in_parentheses("David tends to use parentheses a lot (as he is doing right now). It tends to be quite annoying."))

print(in_parentheses("Open ( only"))

print(in_parentheses("Closed ) only"))

print(in_parentheses("Closed ) before ( open"))

print(in_parentheses("That's a lot of test cases(!)"))

This function in_parentheses uses regular expressions to find text enclosed within parentheses in a given string. It returns the content within the parentheses or an empty string if no text appears in parentheses.

User Alxibra
by
5.9k points