1

It seems that my code isn't converting integers in a list to strings. Here is the are of my code with the problem:

def aidrawboard(aiboard): for i in aiboard: inttostr = aiboard[i] str(inttostr) aiboard[i] = inttostr for i in aiboard: if aiboard[i] == '3': aiboard[i] = '0' break print(aiboard) print("THIS IS THE AI BOARD") print(' | |') print(' ' + aiboard[7] + ' | ' + aiboard[8] + ' | ' + aiboard[9]) print(' | |') print('-----------') print(' | |') print(' ' + aiboard[4] + ' | ' + aiboard[5] + ' | ' + aiboard[6]) print(' | |') print('-----------') print(' | |') print(' ' + aiboard[1] + ' | ' + aiboard[2] + ' | ' + aiboard[3]) print(' | |') 

The code is for a battleship game. an example of list aiboard is [0, 0, 2, 0, 0, 0, 0, 0, 0, 0]

I get the error "TypeError: Can't convert 'int' object to str implicitly", with the error pointing to

print(' ' + aiboard[7] + ' | ' + aiboard[8] + ' | ' + aiboard[9]) 

Sorry if the error is very newbish. This is my first year coding.

1
  • str() returns a string, it doesn't convert an into to a string inplace. Commented Feb 25, 2015 at 3:35

4 Answers 4

4

Since the items stored inside the abiword list are integers, you need to convert the datatype of element (you want to print) to string while printing.

print(' ' + str(aiboard[7]) + ' | ' + str(aiboard[8]) + ' | ' + str(aiboard[9])) 
Sign up to request clarification or add additional context in comments.

Comments

2

Or may you can define a function to print_out the board:

def print_board(aiboard): str_state = map(str, aiboard) print(' | |') print(' ' + str_state[7] + ' | ' + str_state[8] + ' | ' + str_state[9]) print(' | |') print('-----------') print(' | |') print(' ' + str_state[4] + ' | ' + str_state[5] + ' | ' + str_state[6]) print(' | |') print('-----------') print(' | |') print(' ' + str_state[1] + ' | ' + str_state[2] + ' | ' + str_state[3]) print(' | |') 

In this way, easy to read and maintenance.

Comments

2

The problem is that you never set the variable inttostr to the string you create. In your code

for i in aiboard: inttostr = aiboard[i] str(inttostr) aiboard[i] = inttostr 

inttostr remains an int. A couple of ways to fix this.

for i in aiboard: inttostr = aiboard[i] inttostr= str(inttostr) aiboard[i] = inttostr 

or better yet:

for i in aiboard: aiboard[i]= str(aiboard[i]) 

Comments

1

A Pythonic way to convert is:

aiboard_str = [str(i) for i in aiboard] 

Now print the board as before.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.