python - 将列表的字符串元素添加到另一个字符串会导致尝试添加整个列表?
问题描述
我正在尝试编写将接受诸如“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
我不明白它如何认为我正在尝试添加整个列表。所有帮助表示赞赏!
解决方案
您可以使用该split
功能来做到这一点。
inputs = testinput.split('/')
leftof = inputs[0]
rightof = inputs[1]
推荐阅读
- javascript - Bootstrap4:修复和淡入页面底部的页脚
- python - Why do I get this failure and why is mysql set to false?
- android - 多次按下后如何修复按钮停止功能?
- google-earth-engine - 如何附加两个 featureCollections?
- php - 如何使用 SAPI.Spvoice 在 php 中打开 .wav 文件
- vue.js - 如何将此仪表添加到vue项目
- material-ui - 使用未定义而不是 MuiHeader 的样式(@Material-ui v4)
- javascript - 为什么“this.props.match.params.authorName”在 ReactJS 中给出未定义/空值
- java - java中的多进程
- reactjs - 如何修复索引 0 处的“put”中的无效参数:使用 React、Firebase 和 Filepond 时预期的 Blob 或文件