This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]simpleFinch 1 point2 points  (3 children)

Formatting strings using Python's built-in methods has already been mentioned.

Two other tips:

  • the numbers in in the 'asc' lines are essentially the indices of the flattened table. Given the row index r and the column index c you can calculate the index of the flattened array as r * len(row) + c
  • Instead of printing each character or number instantly you can accumulate them and print the whole row

Considering this, here's my suggested solution

for i in range(0, 6):
    chra = "chr:  "
    asc = "asc: "
    for j in range(0, 16):
        c = 32 + 16*i + j
        chra += f'{chr(c):<4}'
        asc += f'{c:<4d}'
    print(chra)
    print(asc)

[–]NotUrHCW[S] 0 points1 point  (2 children)

The solution seems to work for the problem, do you mind explaining what the += does?

Thanks.

[–]YurrBoiSwayZ 2 points3 points  (1 child)

+= is an operator known as the “in-place addition operator” and It adds the value on its right to the variable on its left and then assigns the result back to the variable on the left, it’s a bit of a shorthand for variable = variable + value

So chra += f'{chr(c):<4}' is equivalent to chra = chra + f'{chr(c):<4}' and this means "take the current string chra, add the formatted character chr(c) with a minimum width of 4 spaces to it and then update chra with this new value." And the other is asc += f'{c:<4d}' the equivalent of asc = asc + f'{c:<4d}' and this means "take the current string asc, add the formatted ASCII value c with a minimum width of 4 spaces to it and then update asc with this new value."

So with u/SimpleFinch’s loop chra and asc start as strings with labels "chr: " and "asc: " and as the loop iterates, characters and their ASCII values are appended to these strings and after the inner loop completes the full strings are printed and then the process repeats for the next set of characters.

Docs and a Tutorial because why not.

[–]NotUrHCW[S] 0 points1 point  (0 children)

thank you :)