简体   繁体   English

整数不转换为字符串不转换为字符串(Python)

[英]Integers not converting to strings not converting to strings(python)

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] 列表滑板的示例是[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 我收到错误“ TypeError:无法将'int'对象隐式转换为str”,错误指向

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

Sorry if the error is very newbish. 对不起,如果错误很新。 This is my first year coding. 这是我第一年的编码。

由于在abiword列表中存储的项目是整数,因此在打印时需要将element( 要打印 )的数据类型转换为字符串。

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

Or may you can define a function to print_out the board: 或者,您可以定义一个函数来print_out开发板:

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. 这样,易于阅读和维护。

The problem is that you never set the variable inttostr to the string you create. 问题是您永远不会将变量inttostr设置为您创建的字符串。 In your code 在你的代码中

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

inttostr remains an int. inttostr仍然是一个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])

A Pythonic way to convert is: Python转换的方式是:

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

Now print the board as before. 现在像以前一样打印板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM