Python Forum
List of Strings Problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of Strings Problem
#1
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)
Reply
#2
There are 5 fields in the first string of input and there are 6 fields in the second one. Is that normal?
Reply
#3
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).
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#4
# 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...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing all strings in a list that are of x length Bruizeh 5 3,189 Aug-27-2021, 03:11 AM
Last Post: naughtyCat
  list of strings to list of float undoredo 3 2,693 Feb-19-2020, 08:51 AM
Last Post: undoredo
  Convert a list of integers to strings? Cornelis 3 2,267 Nov-15-2019, 12:13 PM
Last Post: perfringo
  Strings inside other strings - substrings OmarSinno 2 3,662 Oct-06-2017, 09:58 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020