代码不起作用,用户无法输入A或B并将其交换为所有A

时间:2019-06-08 05:12:29

标签: python

我已经创建了一部分代码,用户可以在其中输入字母“ A”或“ B”。该程序的目的是说明是否可以将字母交换为全部字母'A',用户必须在其中输入可能发生的交换大小。

例如,如果用户输入AABB且交换大小为3,则输出应为BBAB,其中两个“ A”变成“ B”,一个“ B”变成“ A”。

目前,我的代码似乎没有替换字母并在表明有错误的地方交换它们。

我的代码如下:

row = input('Enter the row and the side (A/B): ')
swap = int(input('How many places can be swapped? '))

if row[0] == B and row[swap] == B:
  row[0] = replace('B' , 'A') 
  row[swap] = replace('B' , 'A') 
  print(row)

当前代码输出以下内容:

Enter the row and the side (A/B): BBAA
How many places can be swapped? 2
Traceback (most recent call last):
  File "program.py", line 4, in <module>
    if row[0] == B and row[swap] == B:
NameError: name 'B' is not defined

该代码应该已经输出了AAAA。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

问题

  • 您的状况检查有误。 if row[0] == B and row[swap] == B:B此处不是变量,而是字符串文字。因此,您应该使用'B'。进行了这些更正后,代码也无法正常工作。

您可以使用maketranstranslate

row = input('Enter the row and the side (A/B): ')
swap = int(input('How many places can be swapped? '))

table = row.maketrans('AB', 'BA')
s = ''

for i in range(swap): 
    s += row[i].translate(table)
row = s + row[swap:]

print(row)

答案 1 :(得分:1)

如前所述,字符串是不可变的,并且您没有变量A或B。因此,我将它们转换为String文字。并将初始输入转换为列表。

row = list(input('Enter the row and the side (A/B): '))
swap = int(input('How many places can be swapped? '))

for x in range(swap):
    if row[x] == 'A':
        row[x] = 'B'
    else:
        row[x] = 'A'
print(''.join(row))