Siebe Dreesen
Siebe Dreesen

Reputation: 25

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. I want it to be able to return allPrimes with every number on a separate line.

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

Upvotes: 1

Views: 3856

Answers (4)

user8777433
user8777433

Reputation:

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

Upvotes: 0

Rodrigue
Rodrigue

Reputation: 3687

The problem is that you are trying to use the + operator on variables of different types: i is an int; '\n' is a str. To make the + work as a string concatenation you need both variables to be of type str. You can do that with the str function:

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.

Upvotes: 1

vash_the_stampede
vash_the_stampede

Reputation: 4606

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)

Upvotes: 1

chepner
chepner

Reputation: 530960

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))

Upvotes: 3

Related Questions