简体   繁体   English

Python:在变量中添加换行符

[英]Python: add a newline to a variable

I was working on some exercises for school and I can't get over this problem. 我当时正在为学校做一些练习,但我无法克服这个问题。 Is there any way to add a newline to a variable? 有什么办法可以在变量中添加换行符? I tried just concatenating \\n but it doesn't work. 我试着只是串联\\n但是没有用。 I want it to be able to return allPrimes with every number on a separate line. 我希望它能够在单独的行中返回带有每个数字的allPrimes

def all_primes_upto(x):
    allPrimes = ''
    for i in range(x):
        if is_prime(i):
            allPrimes += i + '\n'
    return allPrimes

Don't; 别; your function should return a list of primes; 您的函数应返回素数列表 the caller can join them into a single string if they want. 呼叫者可以根据需要将它们加入单个字符串中。

 def all_primes_upto(x):
     return [i for i in range(x) if is_prime(i)]

 prime_str = '\n'.join(str(x) for x in all_primes_upto(700))

If you instead stored the values in a list, you could then print each item out one by one on individual lines 如果您将值存储在列表中,则可以逐行逐行打印出每个项目

def all_primes_upto(x):
    allPrimes = []
    for i in range(x):
        if is_prime(i):
            allPrimes.append(i)
    return allPrimes

l = all_primes_upto(10)

for i in l:
    print(i)

The problem is that you are trying to use the + operator on variables of different types: i is an int ; 问题是您试图对不同类型的变量使用+运算符: iint '\\n' is a str . '\\n'是一个str To make the + work as a string concatenation you need both variables to be of type str . 为了使+作为字符串连接工作,您需要两个变量都为str类型。 You can do that with the str function: 您可以使用str函数执行此操作:

allPrimes += str(i) + '\n'

Note, however, that the other answers suggesting that your all_primes_upto function could return a list that the caller can join and print are better solutions. 但是请注意,其他答案表明all_primes_upto函数可以返回调用者可以加入并打印的列表,这是更好的解决方案。

Right usage: 正确用法:

def all_primes_upto(x):
    allPrimes = ''
    for i in range(x):
        if is_prime(i):
            allPrimes += i + '\n'
            print(allPrimes)

use print instead of return 使用打印而不是返回

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

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