gpt4 book ai didi

Python打印每个字符?

转载 作者:行者123 更新时间:2023-12-01 04:57:54 26 4
gpt4 key购买 nike

这是我的代码:

#Printing the original list (This was given)
a = ['spam','eggs',100,1234]
a[0:2] = [1,12]
print("This is the original list:", a)
#Prompting user to input data
b = input('Please add your first item to the list: ')
c = input('Please add your second item: ')
a[4:4] = b
a[5:5] = c
#Printing new list
print(a)

当我运行它并将项目添加到列表中时,它会打印那里的每个字符,因此 hello 变成 'h'、'e'、'l'、'l'、'o' 即使数字也能做到这一点,你可以吗帮我解决这个问题吗?

最佳答案

因为当您将字符串添加到列表中时,它们会成为列表中的单个字符:

In [5]: l = [1,2,3]

In [6]: s = "foo"

In [7]: l[1:1] = s

In [8]: l
Out[8]: [1, 'f', 'o', 'o', 2, 3]

如果要将字符串添加到列表末尾,请使用append:

In [9]: l = [1,2,3]

In [10]: s = "foo"

In [11]: l.append(s)

In [12]: l
Out[12]: [1, 2, 3, 'foo']

或者将字符串包装在列表中或使用list.insert:

In [16]: l[1:1] = [s] # iterates over list not the string

In [17]: l
Out[17]: [1, 'foo', 2, 3, 'foo']
In [18]: l.insert(2,"foo")
In [18]: l
Out[19]: [1, 'foo', 'foo', 2, 3, 'foo']

关于Python打印每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com