-2
#!usr/bin/python
import random
seg1='''_________'''
seg2='''|       |'''
seg3a="| Ace   |"
seg32="|  2    |"
seg33="|  3    |"
seg34="|  4    |"
seg35="|  5    |"
seg36="|  6    |"
seg37="|  7    |"
seg38="|  8    |"
seg39="|  9    |"
seg310="| 10    |"
seg3jack="| Jack  |"
seg3queen="|Queen  |"
seg3king="| King  |"
seg4='''|  of   |'''
seg5s="| Spade |"
seg5h="| Heart |"
seg5c="| Clubs |"
seg5d="|Diamond|"
seg6='''|       |'''
seg7='''|_______|'''
a=[seg3a,seg32,seg33,seg34,seg35,seg36,seg37,seg38,seg39,seg310,seg3jack,seg3queen,seg3king]
b=[seg5s,seg5h,seg5c,seg5d]
count=0
count1=0
print seg1*13,'\n',seg2*13#,#'\n'
while count<=12:
    c=random.choice(a)
    print c,
    count+=1
print '\n',seg4*13,'\n'
while count1<=12:
    d=random.choice(b)
    print d,
    count1+=1
print '\n',seg6*13,'\n',seg7*13

Hello. I am trying to make this program which is supposed to print out 13 random cards side by side but it formats really strangely. I know it is caused by the while loop which adds an extra space after it prints something out. Thanks.

Ruochan Liu
  • 167
  • 6
  • By the way, I'd also recommend that you use something more like `topBorder = "____"; blankSpace = " "; numbers = ["| Ace |", ..., "| King |"]; suits = ["| Spades |", ..., "|Diamond|"]`. That way, you don't have to declare so many variables. – humanoid Mar 19 '15 at 01:43

1 Answers1

1

More information can be found here:

How do I keep Python print from adding newlines or spaces?

This can be applied to your code by importing sys and then using:

while count<=12:
    c=random.choice(a)
    sys.stdout.write(c)
    count+=1
sys.stdout.flush()

and the equivalent for the other while loop.

Side note: consider reading some python code by other people. Python users like to keep it short and sweet, and I greatly benefited—at least in terms of coding shortcuts—by doing that. In fact, you could just as well replace that entire loop with:

print "".join([random.choice(a) for i in range(13)])
Community
  • 1
  • 1
humanoid
  • 240
  • 2
  • 11
  • Thank you so much humanoid. I used the .join idea and it works great!! – Ruochan Liu Mar 19 '15 at 01:36
  • No problem. :) Generally, you should try to use `for value in range(x)` whenever you'd have a `for (int i = 0; i++; i < x)` in another language. You should also check out [range](https://docs.python.org/2/library/functions.html#range)'s more advanced functions – humanoid Mar 19 '15 at 01:38