0

I have the below function that loops through two lists and prints out a selection of vegetables and then fruits.

def Selection():
    print("VEGETABLES FOR THE WEEK:\n")
    for veg in veg_selection:
        print(veg.upper())
    print("\n")
    print("FRUITS FOR THE WEEK:\n")
    for fruit in fruit_selection:
        print(fruit.upper())

So the result could look like:

VEGETABLES FOR THE WEEK:

BROCOLLI
PEAS
CARROTS
SWEET CORN
WHITE ONIONS


FRUITS FOR THE WEEK:

GRAPEFRUIT
CHERRIES
ORANGE
COCONUT
RASPBERRIES

I'm struggling to get my head around assigning the printed results of the function to a single variable that contains the formatted string. Would I need to save the results as a text file and then read it in again? Can I just use text concatenation? I'm unsure how to deal with the for loops in the function? Any help really appreciated.

4 Answers 4

5

One of solutions would be to store all itermediate strings to container and join them afterwards. Quoting docs:

string.join(words[, sep]) Concatenate a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character. It is always true that string.join(string.split(s, sep), sep) equals s.

So sample code would look like:

import os

def selection():
    strings = []
    strings.append("VEGETABLES FOR THE WEEK:\n")
    for veg in veg_selection:
        strings.append(veg.upper())
    strings.append("\n")
    strings.append("FRUITS FOR THE WEEK:\n")
    for fruit in fruit_selection:
        strings.append(fruit.upper())
    return os.linesep.join(strings)

s = selection()  # s now contains output string, and nothing is printed
print(s)  # print whole string at once

os.linesep is cross-os constant with correct newline character.

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Also, semi-related question: Good way to append to a string.

Sign up to request clarification or add additional context in comments.

Comments

1

Probably the simplest way to do it is to just add an extra step appending the text to your variable wherever you need to. See below:

def Selection():
    output_text = "VEGETABLES FOR THE WEEK:\n"
    print("VEGETABLES FOR THE WEEK:\n")
    for veg in veg_selection:
        output_text += veg
        print(veg.upper())
    output_text += "\n"
    print("\n")
    output_text += "FRUITS FOR THE WEEK"
    print("FRUITS FOR THE WEEK:\n")
    for fruit in fruit_selection:
        output_text += fruit
        print(fruit.upper())

You could change your code to output the output_text string at the end instead of printing each line too.

Comments

1

You can just concatenate to a single string variable like so:

def Selection():
    output = "VEGETABLES FOR THE WEEK:\n"
    for veg in veg_selection:
        output += veg.upper() + "\n"
    output += "\nFRUITS FOR THE WEEK:\n"
    for fruit in fruit_selection:
        output += fruit.upper() + "\n"

You can then either print the string straight away by adding to the end:

print(output)

or return the string for use elsewhere by adding at the end:

return output

Comments

1

Turn your function into generator:

def Selection():
    yield "VEGETABLES FOR THE WEEK:\n"
    for veg in veg_selection:
        yield veg.upper()
    yield "\n"
    yield "FRUITS FOR THE WEEK:\n"
    for fruit in fruit_selection:
        yield fruit.upper()

Then, turning into a string is trivial:

'\n'.join(Selection())

To print the result:

for line in Selection():
    print(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.