Skip to main content
 首页 » 编程设计

python之如何将以下输出更改为正确的字符串

2025年05月04日33lidabo

我正在尝试编写一个聊天机器人,它将打印一个字符串,其中包含 n 乘以我名字的第一个字母,然后是 "n",然后是 n-1 次我名字中的第二个字母。

例子:

name: chris 
n = 5 (since there are 5 letters in the name) 
n-1 = 4 
first letter of the name: c 
second letter of the name: h 

我要生成的字符串:ccccc5hhhh

我的问题:生成的字符串在我不想要的括号中。我希望字符串与“ccccc5hhhh”完全一样,没有空格;全部在一行中,但我不断收到 ['c','c','c','c','c']5['h','h','h','h' ] 作为输出。

st1 = input("First name? ==> ") 
 
print("Please enter the first letter of your name") 
letter = input ("First letter? ==>? ") 
 
if (letter == st1[0]): 
    # initializing list of lists 
    test_list = st1[0] 
    test_list1 = st1[1] 
 
# repeat letters n times 
res =  [ele for ele in test_list for i in range(len(st1))] 
res2 =  [ele for ele in test_list1 for i in range(len(st1)-1)] 
 
# printing result 
print(str(res), len(st1), str(res2)) 

请您参考如下方法:

您正在寻找 join功能。不过,将 , 与您的参数一起使用会插入一个空格。

要获得您正在寻找的结果,您需要:

print(''.join(res) + str(len(st1)) + ''.join(res2))