2

Take a look eat the list below

nursery_rhyme = [
'This is the house that Jack built.',
'This is the malt that lay in the house that Jack built.',
'This is the rat that ate the malt that lay in the house that Jack built.',
'This is the cat that killed the rat that ate the malt that lay in the house that Jack built.'
]

The function below is supposed to return the lines of the list above within the specified range

def recite(start_verse, end_verse):
    lines = []
    start = start_verse
    lines.append(nursery_rhyme[(start-1)])
    while start < end_verse:
        start += 1
        line = nursery_rhyme[start-1]
        lines.append(line)
    return (lines)

In use:

print(recite(1,2))

Output:

['This is the house that Jack built.', 'This is the malt that lay in the house that Jack built.']

How do I get my output to look like this:

[
 'This is the house that Jack built.',
 'This is the malt that lay in the house that Jack built.'
]
001
  • 13,291
  • 5
  • 35
  • 66
Wakayamba
  • 23
  • 3
  • 1
    Have a look at [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join) or maybe [`PrettyPrinter`](https://docs.python.org/3/library/pprint.html) – 001 Aug 15 '22 at 17:00
  • 1
    Lists don't have lines. You are conflating data and how that data is displayed. – John Coleman Aug 15 '22 at 17:02
  • Side note: simplify your code with: [Understanding slicing](https://stackoverflow.com/q/509211) – 001 Aug 15 '22 at 17:06

3 Answers3

1

Here's a quick and easy function which will output the lines, as would be shown on paper.

The function below uses the following techniques:

  • List slicing to output only the desired lines.
  • The sep argument of the print function, which tells print which character to print between each item, in this case, a new line.
  • The 'splat' operator (*) which expands (or unpacks) the list elements, thus enabling print to separate each with a new line.

For example:

def recite(lines, start, end):
    print(*lines[start-1:end], sep='\n')

>>> recite(nursery_rhyme, 1, 2)

Output:

This is the house that Jack built.
This is the malt that lay in the house that Jack built.
S3DEV
  • 8,768
  • 3
  • 31
  • 42
0

you may try it like this...

def recite(start_verse, end_verse):
  for line in (start_verse-1, end_verse):
    print(nursery_rhyme[line])


recite(1,2)
Abhishek Kumar
  • 383
  • 4
  • 18
0

Instead of printing whole list at once you can loop through each string and print it out:

for i in recite(1, 2):
    print(i)
Yenz1
  • 84
  • 1
  • 9