Replace number with symbol in a list of lists

Question:

I need to replace 0 in a list of lists with dot ".". I aslo need to replace 1 with "o" and 2 with "*"
It should be something like chess board. So far I have this and I am stuck with the replacement. Thank you for your help! 🙂

chess =[
    ["0 1 0 1 0 1 0 1 "],
    ["1 0 1 0 1 0 1 0 "],
    ["0 1 0 1 0 1 0 1 "],
    ["0 0 0 0 0 0 0 0 "],
    ["0 0 0 0 0 0 0 0 "],
    ["2 0 2 0 2 0 2 0 "],
    ["0 2 0 2 0 2 0 2 "],
    ["2 0 2 0 2 0 2 0 "]]


def prt(n):
    for i in range(len(n)):
        for j in range(len(n[i])):
            if n[j] == "0":
                n[j] = "."
            print(n[i][j])
       
prt(chess)

Output should be something like this

Final product

Asked By: Jimmy

||

Answers:

You can try it by using the replace function for strings and iterating through the lines itself:

def print_chess(chess):
    for line_list in chess:
        line = line_list[0]
        line = line.replace("0", ".")
        line = line.replace("1", "o")
        line = line.replace("2", "*")
        print(line)

Edit: thanks to @Muhammad Rizwan for pointing out that replace returns the result.

Answered By: Jasmin Heifa

In each list of your list you store one string, i.e. "0 1 0 1 0 1 0 1 ".
So your loop doesn’t work:

for i in range(len(n)): 
    for j in range(len(n[i])):  # len(n[i]) is always 1
        if n[j] == "0":  # n[j]: "0 1 0 1 0 1 0 1 " equal "0" is False
            n[j]="."

A comparison for an individual number won’t work.
In order for you to get the individual number you can use the split method on the only element of your list. So you need to access it via the 0 index and call split on that element.
Build a new list of list for storing the modified values.

Using this, you can expand your if logic to check for "1" and "2" and for any other value to not change the value.

chess = [
    ["0 1 0 1 0 1 0 1 "],
    ["1 0 1 0 1 0 1 0 "],
    ["0 1 0 1 0 1 0 1 "],
    ["0 0 0 0 0 0 0 0 "],
    ["0 0 0 0 0 0 0 0 "],
    ["2 0 2 0 2 0 2 0 "],
    ["0 2 0 2 0 2 0 2 "],
    ["2 0 2 0 2 0 2 0 "]]

def prt(n):
    letters = " abcdefgh"
    # Initialize chessboard with letters
    board = [letters]
    # set enumerates start value to 1
    for i, line in enumerate(n, 1):
        numbers = line[0].split()  # splits at whitespace
        line_list = []
        for num in numbers:
            if num == "0":
                line_list.append(".")
            elif num == "1":
                line_list.append("o")
            elif num == "2":
                line_list.append("*")
            else:
                line_list.append(num)
        # Concatenate current line index at beginning and end of line_list
        board.append([i] + line_list + [i])
    # Append letters as last line of board
    board.append(letters)
    # Print new chess board
    for line in board:
        for el in line:
            print(el, end=" ")
        print()

prt(chess)

Changes:

  • Setting letters as first and last element of board
  • Make use of built-in function enumerate
  • Set start value of enumerate to 1 to get a modified index

This will give you the desired outcome:

  a b c d e f g h 
1 . o . o . o . o 1 
2 o . o . o . o . 2 
3 . o . o . o . o 3 
4 . . . . . . . . 4 
5 . . . . . . . . 5 
6 * . * . * . * . 6 
7 . * . * . * . * 7 
8 * . * . * . * . 8 
  a b c d e f g h 
Answered By: Wolric

You should use the replace function for strings.

chess =[
    ["0 1 0 1 0 1 0 1 "],
    ["1 0 1 0 1 0 1 0 "],
    ["0 1 0 1 0 1 0 1 "],
    ["0 0 0 0 0 0 0 0 "],
    ["0 0 0 0 0 0 0 0 "],
    ["2 0 2 0 2 0 2 0 "],
    ["0 2 0 2 0 2 0 2 "],
    ["2 0 2 0 2 0 2 0 "]]


def prt (n):
    new_list = []
    for line in n:
        line = line[0]
        line = line.replace('0','.')
        line = line.replace('1', 'o')
        line = line.replace('2', '*')
        temp = []
        temp.append(line)
        new_list.append(temp)
    print(new_list)
       
prt(chess)
Answered By: Muhammad Rizwan

I guess if you just need to print the layout, this would be a way to solve it:

from string import ascii_lowercase

chess = [
    ["0 1 0 1 0 1 0 1"],
    ["1 0 1 0 1 0 1 0"],
    ["0 1 0 1 0 1 0 1"],
    ["0 0 0 0 0 0 0 0"],
    ["0 0 0 0 0 0 0 0"],
    ["2 0 2 0 2 0 2 0"],
    ["0 2 0 2 0 2 0 2"],
    ["2 0 2 0 2 0 2 0"]
]

def prt(chess):
    joined_chars = "".join(chess[0][0].split()) # joining the first list in chess to single string: 01010101
    letters = " ".join([ascii_lowercase[i] for i in range(len(joined_chars))]) # Creating a list of letters that is the length of the joined_chars and joins it with spaces: a b c d e f g h
    print(f"  {letters}") # prints the letters starting with two spaces
    for index, lst in enumerate(chess): # Using enumerate to get the index while running through chess
        printable = lst[0].replace("0", ".").replace("1", "o").replace("2", "*")
        print(f"{index+1} {printable} {index+1}") # prints the index (starts at 0) + 1 to get the correct values.
    print(f"  {letters}") # prints the letters starting with two spaces

prt(chess)

Result:

  a b c d e f g h
1 . o . o . o . o 1
2 o . o . o . o . 2
3 . o . o . o . o 3
4 . . . . . . . . 4
5 . . . . . . . . 5
6 * . * . * . * . 6
7 . * . * . * . * 7
8 * . * . * . * . 8
  a b c d e f g h
Answered By: user56700

Thank you so much for your help.
So far I have managed this, but I have no idea how to put numbers at the beginning and at the end of the line like in the picture.

enter image description here

My new code:

    chess =[
    ["0 1 0 1 0 1 0 1 "],
    ["1 0 1 0 1 0 1 0 "],
    ["0 1 0 1 0 1 0 1 "],
    ["0 0 0 0 0 0 0 0 "],
    ["0 0 0 0 0 0 0 0 "],
    ["2 0 2 0 2 0 2 0 "],
    ["0 2 0 2 0 2 0 2 "],
    ["2 0 2 0 2 0 2 0 "]]

letters =["a b c d e f g h"]
numbers =["1 2 3 4 5 6 7 8"]

def prt(x):
    num_let(letters) 
    for list in x:
        new = list[0]
        new = new.replace("0", ".")
        new = new.replace("1", "o")
        new = new.replace("2", "*")
        print(new)
    num_let(letters)
   
def num_let (y):
    print(y[0])

prt(chess)

This gives me this:

a b c d e f g h
. o . o . o . o 
o . o . o . o .
. o . o . o . o
. . . . . . . .
. . . . . . . .
* . * . * . * .
. * . * . * . *
* . * . * . * .
a b c d e f g h
Answered By: Jimmy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.