繁体   English   中英

如何将字符串放入 python 中的特定索引 position

[英]How to put a string in a specific index position in python

我试图根据 awnser 将字符串 '^' 放在我的代码中的特定索引 position 中,这是我的代码。

mylist = ['', 'O', '']
from random import shuffle

def shuffle_list(mylist):
    shuffle(mylist)
    return mylist


def player_guess():
    guess = ''
    while guess not in ['0', '1', '2']:
        guess = input("Pick a number from 0, 1 or 2: ")

    return int(guess)

myindex = player_guess()

def check_guess(mylist, guess):
    if mylist[guess] == 'O':
        print("Correct")
        print(mylist)
    else:
        print('Wrong guess!')
        correct_pos = {mylist.index('O')}
        print(f"Your guess was at position {guess} the correct position was {correct_pos} \n {mylist} \n")
 

# INITAL LIST
mylist = ['', 'O', '']
# SHUFFLE LIST
mixedup_list = shuffle_list(mylist)
# USER GUESS
guess = player_guess()
# CHECK GUESS
check_guess(mixedup_list, guess)

我不希望我的 output 是这个 ['','','O'] 这是典型的 output 在你弄错问题后我希望它看起来像 ['','','O']在新行的“O”下方带有“^”符号,我将如何做这样的事情,我需要添加什么?

这将打印出 O 在列表中的位置

def check_guess(mylist, guess):
    if mylist[guess] == 'O':
        print("Correct")
        print(mylist)
    else:
        print('Wrong guess!')
        correct_pos = {mylist.index('O')}
        print(f"Your guess was at position {guess} the correct position was {correct_pos} \n {mylist}")
        carrot_string = ' '*(3+mylist.index('O')*4) + '^'
        print(carrot_string)

第一个元素从 position 3 开始,并根据其在列表中的位置增加 4

暂无
暂无

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

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