简体   繁体   English

将函数打印输出分配给字符串变量

[英]Assigning function print output to string variable

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? 我不确定如何处理函数中的for循环? Any help really appreciated. 任何帮助真的很感激。

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. string.join(words[, sep])将插入有sep出现的单词列表或元组连接起来。 The default value for sep is a single space character. sep的默认值是单个空格字符。 It is always true that string.join(string.split(s, sep), sep) equals s. string.join(string.split(s, sep), sep)等于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. os.linesep是带有正确换行符的跨OS常量。

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. 这可以是单个字符,例如对于POSIX为'\\ n',也可以是多个字符,例如对于Windows为'\\ r \\ n'。 Do not use os.linesep as a line terminator when writing files opened in text mode (the default); 写入以文本模式打开的文件时,请不要使用os.linesep作为行终止符(默认); use a single '\\n' instead, on all platforms. 在所有平台上都使用一个'\\ n'代替。

Also, semi-related question: Good way to append to a string . 另外,半相关的问题: 追加到字符串的好方法

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. 您可以更改代码以在末尾输出output_text字符串,而不用打印每行。

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM