84.0k views
3 votes
6.12 LAB: Warm up: Parsing strings (1) Prompt the user for a string that contains two strings separated by a comma. (1 pt) Examples of strings that can be accepted: Jill, Allen Jill , Allen Jill,Allen Ex: Enter input string: Jill, Allen (2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. (2 pts)

User Taek
by
4.8k points

2 Answers

4 votes

Final answer:

To prompt the user for a string that contains two strings separated by a comma in Python, you can use the input() function and the split() method. Here's an example code snippet that demonstrates this.

Step-by-step explanation:

To prompt the user for a string that contains two strings separated by a comma, you can use the input() function in Python. You can then use the split() method to split the input string into two separate strings based on the comma. Here's an example:

valid = False

while not valid:
input_string = input('Enter input string: ')
if ',' not in input_string:
print('Error: Input string does not contain a comma.')
else:
string1, string2 = input_string.split(',')
valid = True

print('String 1:', string1.strip())
print('String 2:', string2.strip())

In this example, we use a while loop to continue prompting the user until a valid string is entered. The strip() method is used to remove any leading or trailing spaces from the extracted strings.

User Matec
by
4.4k points
1 vote

Answer:

Step-by-step explanation:

The following code is written in Python. It is a loop that asks the user for an input. If it contains a comma then it removes whitespace, splits it into two words, and prints each word seperately, and exits the loop. If it does not contain a comma then it prompts the user for another input.

while True:

string = input("Enter input string: ")

if ',' in string:

string = string.replace(" ", '')

string_split = string.split(',')

print("First word: " + string_split[0])

print("Second word: " + string_split[1])

break

6.12 LAB: Warm up: Parsing strings (1) Prompt the user for a string that contains-example-1
User Mcmlxxxvi
by
3.9k points