Python - spaces - python

I can't get over this little problem.
The second is right.
How can i print without spaces?
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print "*",
else: print "+",
print
thanks for help!

By not using print plus a comma; the comma will insert a space instead of a newline in this case.
Use sys.stdout.write() to get more control:
import sys
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: sys.stdout.write("*")
else: sys.stdout.write("+")
print
print just writes to sys.stdout for you, albeit that it also handles multiple arguments, converts values to strings first and adds a newline unless you end the expression with a comma.
You could also use the Python 3 print() function in Python 2 and ask it not to print a newline:
from __future__ import print_function
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print("*", end='')
else: print("+", end='')
print()
Alternatively, join the strings first with ''.join():
def square(n):
for i in range(n):
print ''.join(['*' if i in (0, n-1) or j in (0, n-1) else '+' for j in xrange(n)])

Can you try to use sys.stdout.write("+") instead of print "+" ?

In python 3 you can overwrite the print behaviour, here this will solve your problem:
print("+", end="")

Related

How do i know the reader is at the end value of generator in python

How do i know the reader is at the end value of generator in python??
Example: print 100 primes from 1 to 100
def gen(m):
def snt(n):
if n<1:
return False
else:
ktra=True
for i in range(2,n):
if n%i==0:
ktra=False
return ktra
for i in range(1,m+1):
if snt(i)==True:
yield i
for i in gen(100):
print(i,end=",")
And this is result:
1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,
*comma in number 97
But I want dot in number 97:
1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97.
What can I do?
You don't know in advance which value is the last, but you know which value is the very first. Print the separator before every value except the first one.
first = True
for i in range(10): # range as an example
if first:
first = False
else:
print(",", end="")
print(i, end="") # see note 1
print(".")
# [1] add flush=True to see the output on terminal as it arrives
There is also the str.join which is convenient to use.
print(",".join(str(i) for i in range(10)), end=".\n") # with the trailing dot
The main difference is that the code above prints a value immediately when it is available, but the join needs all values to be collected.

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
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; '\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.
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

(Python 3) avoid printing comma at the end in print(variableName,end=',')

I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')

How to create a right triangle with asterisk without def function?

So far what I have is:
base = int(input("Enter a value"))
for row in range(base):
for colomb in range(row+1):
print('*', end='')
print()
You were nearly there. You just need to unindent the last print(). Example -
for row in range(base):
for colomb in range(row+1):
print('*', end='')
print()
Sharon's answer is the quickest solution to make the code you have work, but you could also do fewer runs through for loops by just printing (once) the entire string. "a" * 3 is "aaa", for instance, so you could do:
for row in range(1, base+1): # now the range runs [1-base] instead of [0-base-1]
print("*" * row)

python asterisk triangle without using y* "*"

I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is
This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s
This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")
I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.
There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.

Categories

Resources