Python Forum

Full Version: List of Strings Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The input is a list of strings, I need to add code below it (and fix indentation and variable names if needed) so that the code will print a story for each string in the list. Any suggestions?
# create the input
input = ["Pat,Smith,girl,65 Elm Street,eat", "John,Doe,Boy,25,123 Candy Lane, tickle"]

# split at the comma
pieces = input.split(",")

# initialize the variables
firstName = pieces[0]
lastName = pieces[1]
gender = pieces[2]
address = pieces[3]
verb = pieces[4]

# create the story
start = "Once there was a " + gender + " named " + firstName + "."
next1 = "A good " + gender + " living at " + address + "."
next2 = "One day, a wicked witch came to the " + lastName + " house."
next3 = "The wicked witch was planning to " + verb + " " + firstName + "!"
ending = "But " + firstName + " was smart and avoided the wicked witch."

# print the story
print(start)
print(next1)
print(next2)
print(next3)
print(ending)
There are 5 fields in the first string of input and there are 6 fields in the second one. Is that normal?
Start by finding the length of the list for the loop. Next initialise the loop. You need to specify which element in the list you want to split (BTW it can't be a static value have to change with the loop).
# create the input
input = ["Pat,Smith,girl,65 Elm Street,eat", "John,Doe,Boy,25,123 Candy Lane, tickle"]
 
# split at the comma
for inp in input:
  pieces = inp.split(",")
 
  # initialize the variables
  firstName = pieces[0]
  lastName = pieces[1]
  gender = pieces[2]
  address = pieces[3]
  verb = pieces[4]
   
  # create the story
  start = "Once there was a " + gender + " named " + firstName + "."
  next1 = "A good " + gender + " living at " + address + "."
  next2 = "One day, a wicked witch came to the " + lastName + " house."
  next3 = "The wicked witch was planning to " + verb + " " + firstName + "!"
  ending = "But " + firstName + " was smart and avoided the wicked witch."
   
  # print the story
  print(start)
  print(next1)
  print(next2)
  print(next3)
  print(ending)
this may help you...