Printing issues when moving from Python 2 to 3 with code - python

I have a code that I am trying to convert but it's written in Python 2 and I would like to print this code in Python 3. However, it's not able to print in matrix format. I am getting output in an unrecognizable table format.
The code is following:
for n in cols:
print('/t',n),
print
cost = 0
for g in sorted(costs):
print('\t', g)
for n in cols:
y = res[g][n]
if y != 0:
print (y),
cost += y * costs[g][n]
print ('\t'),
print
print ("\n\nTotal Cost = ", cost)
The expected output is in the following format:
|0 |A |B |C |D |E |
|- |- |- |- |- |- |
|W | | |20| | |
|X | |40|10| |20|
|Y | |20| | |30|
|Z | | | | |60|
Total Cost = 1000
Could you suggest what changes I need to make in this code?

In py 2 print did not have parenthesis, in py3 is a must.
python3 simple print
# in py3 a print must be like
print("my text")
python3 print with no newline / carriage return
Also in your py2 code you have print ('\t'), please mind the comma after print => which means do not add a newline after print.
In python3 would translate to
print('\t', end='')

Your print calls must always be enclosed in parenthesis like this:
print("\t", n)

Another thing - whenever you see the Python 2 print command with
a comma at the end, such as
print y,
you need to change that line to:
print(y,end="")
This will print the variable without a new line.

Related

Writing to a file py

if anyone can help me I need my code to display as such:
Hammad | Won | 5
The code I'm using is:
f = open("Statistics.txt", "a")
f.write(str(player_name) +''+ str(Outcome)+''+str(max_guesses)+"\n"
f = open("Statistics.txt", "r")
print(f.read())
f.close()
I need the output to be:
Hammad | Won | 6
Instead I'm getting:
Hammad Won 6
Python does not add | character automatically while string concatenation, you have to do it manually,
f.write(str(player_name) +' | '+ str(Outcome)+' | '+str(max_guesses)+"\n")
PS : f.write need a closing parenthesis(all functions do)
Try replacing the write line with:
f.write(f'{player_name} | {Outcome} | {max_guesses}\n')
Replace f.write with this
f.write(str(player_name)+'|'+str(Outcome)+'|'+str(max_guesses)+"\n"

How can I create a table in python?

I have found a way to list all the alt codes but I want to put them in a
table so it looks something like this.
This is what I have tried:
variable = -1
for i in range(55295):
print("---------")
variable = variable + 1
print(str(variable) + " " + chr(variable))
This code will print all the alt codes.
To get it into a table I tried this. (It has a time delay)
import time
variable = -1
#for i in range(55295):
for i in range(15):
print("---------")
variable = variable + 1
print(" | "+ str(variable) + " | " + chr(variable) + " | ")
time.sleep(0.0001)
print("---------------------------------------------------")
I have run out of ideas, can you help please?
(This is the first time i've asked a question on here.)
You cannot print characters with such low codes on a 21st century system. The characters in the image are those that appeared on old MS-DOS systems (according to Wikipedia: Code Page 437). However, modern systems work with Unicode fonts, and the codes below 32 (space) are control codes, reserved for special purposes. The code 9, for example, inserts a Tab, and 10 puts the text cursor on a new line.
(This was also the case on those old systems but you could circumvent this by writing immediately into the video buffer. Nowadays, that is no longer an option on most computers.)
To get the modern equivalent of the old characters, you need a lookup list that translates them. I copied mine from the wiki page linked to above. Note that there is no official representation of the code 0000; I changed it to a space. This is only for the control codes below 32. There are a few codes above 126 that also may not show "correctly" (as in "not as on antique computers" 😄), but you can look them up on the wiki page.
To correctly align one- and two-digit numbers, use print formatting. Aligning can be done with functions such as rjust and .format; but, coming from a C background, I prefer what the documentation calls "Old style formatting" (https://docs.python.org/3/library/stdtypes.html#old-string-formatting).
cp437 = [0x0020, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB,
0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, 0x25BA, 0x25C4, 0x2195, 0x203C,
0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194,
0x25B2, 0x25BC]
for i in range(15):
print("+----+-----+")
print("| %2d | %s |" % (i, chr(cp437[i])))
print("+----+-----+")
This produces the following table:
+----+-----+
| 0 | |
+----+-----+
| 1 | ☺ |
+----+-----+
| 2 | ☻ |
+----+-----+
| 3 | ♥ |
+----+-----+
| 4 | ♦ |
+----+-----+
| 5 | ♣ |
+----+-----+
| 6 | â™  |
+----+-----+
| 7 | • |
+----+-----+
| 8 | â—˜ |
+----+-----+
| 9 | â—‹ |
+----+-----+
| 10 | â—™ |
+----+-----+
| 11 | ♂ |
+----+-----+
| 12 | ♀ |
+----+-----+
| 13 | ♪ |
+----+-----+
| 14 | ♫ |
+----+-----+
You can try to use the pyplot table method: I have modified and extended your example code so that it looks like:
import matplotlib.pyplot as plt
import time
variable = 96
chars = []
#for i in range(55295):
for i in range(26):
print("---------")
variable = variable + 1
chars.append([str(variable), chr(variable)])
print(" | "+ str(variable) + " | " + chr(variable) + " | ")
time.sleep(0.0001)
print("---------------------------------------------------")
plt.figure('Table')
plt.axis('off')
columns=['Alt Codes','Characters']
tab = plt.table(cellText=chars,loc='center',cellLoc='center',colLabels=columns)
plt.show()
The result looks like:
png file of the table saved with matplotlib
I did not succeed to make the characters with alt-code starting from 0 visible in the table (only in the console).

Print multiline strings side-by-side

I want to print the items from a list on the same line.
The code I have tried:
dice_art = ["""
-------
| |
| N |
| |
------- ""","""
-------
| |
| 1 |
| |
------- """] etc...
player = [0, 1, 2]
for i in player:
print(dice_art[i], end='')
output =
ASCII0
ASCII1
ASCII2
I want output to =
ASCII0 ASCII1 ASCII2
This code still prints the ASCII art representation of my die on a new line. I would like to print it on the same line to save space and show each player's roll on one screen.
Since the elements of dice_art are multiline strings, this is going to be harder than that.
First, remove newlines from the beginning of each string and make sure all lines in ASCII art have the same length.
Then try the following
player = [0, 1, 2]
lines = [dice_art[i].splitlines() for i in player]
for l in zip(*lines):
print(*l, sep='')
If you apply the described changes to your ASCII art, the code will print
------- ------- -------
| || || |
| N || 1 || 2 |
| || || |
------- ------- -------
The fact that your boxes are multiline changes everything.
Your intended output, as I understand it, is this:
------- -------
| || |
| N || 1 | ...and so on...
| || |
------- -------
You can do this like so:
art_split = [art.split("\n") for art in dice_art]
zipped = zip(*art_split)
for elems in zipped:
print("".join(elems))
# ------- -------
# | || |
# | N || 1 |
# | || |
# ------- -------
N.B. You need to guarantee that each line is the same length in your output. If the lines of hyphens are shorter than the other, your alignment will be off.
In the future, if you provide the intended output, you can get much better responses.
Change print(dice_art[i], end='') to:
print(dice_art[i], end=' '), (Notice the space inbetween the two 's and the , after your previous code)
If you want to print the data dynamically, use the following syntax:
print(dice_art[i], sep=' ', end='', flush=True),
A join command should do it.
dice_art = ['ASCII0', 'ASCII1', 'ASCII2']
print(" ".join(dice_art))
The output would be:
ASCII0 ASCII1 ASCII2

Issue with printing formatted string in Python

I am trying to parse a text document line by line and in doing so I stumbled onto some weird behavior which I believe is caused by the presence of some kind of ankh symbol (☥). I am not able to copy the real symbol here.
In my code I try to determine whether a '+' symbol is present in the first characters of each line. To see if this worked I added a print statement containing a boolean and this string.
The relevant part of my code:
with open(file_path) as input_file:
content = input_file.readlines()
for line in content:
plus = '+' in line[0:2]
print('Plus: {0}, line: {1}'.format(plus,line))
A file I could try to parse:
+------------------------------
row 1 with some content
+------+------+-------+-------
☥+------+------+-------+------
| col 1 | col 2 | col 3 ...
+------+------+-------+-------
|_ valu | val | | dsf |..
|_ valu | valu | ...
What I get as output:
Plus: True, line: +------------------------------
Plus: False, line: row 1 with some content
Plus: True, line: +------+------+-------+-------
♀+------+------+-------+------
Plus: False, line: | col 1 | col 2 | col 3 ...
Plus: True, line: +------+------+-------+-------
Plus: False, line: |_ valu | val | | dsf |..
Plus: False, line: |_ valu | valu | ...
So my question is why does it just print the line containing the symbol without the 'Plus: True/False'. How should I solve this?
Thanks.
What you are seeing is the gender symbol. It is from the original IBM PC character set and is encoded as 0x0c, aka FormFeed, aka Ctrl-L.
If you are parsing text data with these present, they likely were inserted to indicate to a printer to start a new page.
From wikipedia:
Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return. The form feed character code is defined as 12 (0xC in hexadecimal), and may be represented as control+L or ^L.

How can I use a list-like type to generate a markdown with string.Template python?

I have the following Template
from string import Template
myTemplate = '''$heading
| Name | Age |
| ---- |---- |
'''
The problem is that I don't know when writing the template how many people there will be in the table. So I would like to pass in a list of tuples such as:
myTemplate.substitute(...=[("Tom", "23"), ("Bill", "43"), ("Tim", "1")])
How can this be done? If I just add in a placeholder for the list with tuples, this would not work since the surrounding formatting of the data would be lost.
I would like the template to capture the formatting and the list to capture the data and keep those two elements separate.
The result should be as follows:
| Name | Age |
| ---- |---- |
| Tom | 23 |
| Bill | 43 |
| Tim | 1 |
There may be a reason for not wanting to import a fully featured templating engine, such as wanting to run the code in a seriously resource-limited environment. If so, it's not hard to do this in a few lines of code.
The following can cope with a list of tuples of up to 26 elements itentified as $A to $Z in the template string, and returns a list of template expansions.
from string import Template
def iterate_template( template, items):
AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
return [ Template(template).safe_substitute(
dict(zip( AZ, elem ))) for elem in items ]
Edit: for efficiency I should probably have instantiated the Template once and used it multiple times in the list comprehension:
def iterate_template( template, items):
AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
tem = Template(template)
return [ tem.safe_substitute( dict(zip( AZ, elem ))) for elem in items ]
examples of use
>>> table = [('cats','feline'), ('dogs','canine')]
>>> iterate_template('| $A | $B |', table )
['| cats | feline |', '| dogs | canine |']
>>> x=Template('$heading\n$stuff').substitute(
heading='This is a title',
stuff='\n'.join(iterate_template('| $A | $B | $C |',
[('cats','feline'), ('dogs', 'canine', 'pack')] ) ) # slight oops
)
>>> print(x)
This is a title
| cats | feline | $C |
| dogs | canine | pack |
I recommend Mustache. This is a simple template engine that can do what you need.

Categories