I've spent a couple of days on this Lab and I'm just struggling to get appropriate outputs. If someone can show me where to go with this, or if you have the code itself to share, I can reverse-engineer that. Thanks for any help!
6.6 Warm up: Parsing strings (Python 3)
(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)
Ex:
Enter input string: Jill Allen
Error: No comma in string.
Enter input string: Jill, Allen
(3) Using string splitting, extract the two words from the input string and then remove any spaces. Output the two words. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters
q
to quit. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
Hi I see you are learning Python. Everyone should know it, it's great!
Given that these are somewhat considered Python basics, I shall provide you with the resources to learn how to solve this yourself.
If you are given the answer then you won't learn this wonderful languageso let me ammend your labsheet with helpful links and instructions:
You need string user input. Look at the
raw_input()
function on this turorial site, don't forget to store the return value of the function.You need to check if a string contains another string, check this SO answer and store it as a boolean (for this answer lets call it
inputHasComma
)You will need a
while
loop, here is a tutorial on while loops, make the condition useinputHasComma
(that you defined earlier).To split a string, here is a nice example. Store the result of the split into a variable (it should be a list) and then get the elements that you want out of the list like so:
Do an
if
condition before you check for commas that uses abreak
(tutorial onbreak
here). Look at the first example for an if condition that checks if a string equals another string on this tutorial site.This should get you through the lab! Good luck. :)