首页 > 解决方案 > 将列表的字符串元素添加到另一个字符串会导致尝试添加整个列表?

问题描述

我正在尝试编写将接受诸如“123/456”之类的输入并从斜线的每一侧分离出内容的代码。因此,正确答案将被放入 2 个变量中,第一个变量名为“leftof”,值为“123”,第二个变量名为“rightof”,值为“456”。

我的代码:

testinput = "123/456"

inputlist = []
inputlist = list(testinput)

print(inputlist[0])
print("list elements are of ", type(inputlist[0]))

leftof = ''
rightof = ''

bool = 0


for x in inputlist :   
    if [x] == ("/") :
        bool =1
    else :
        if bool == 0:           
            leftof = leftof + [x]
        if bool == 1:           
            rightof = rightof + [x]    

print("left of slash is ", leftof)
print("right of slash is ", rightof)

还有我的回溯:

C:\python>python ddd.py
1
list elements are of  <class 'str'>
Traceback (most recent call last):
  File "ddd.py", line 20, in <module>
    leftof = leftof + [x]
TypeError: can only concatenate str (not "list") to str

我不明白它如何认为我正在尝试添加整个列表。所有帮助表示赞赏!

标签: python

解决方案


您可以使用该split功能来做到这一点。

inputs = testinput.split('/')
leftof = inputs[0]
rightof = inputs[1]

推荐阅读