首页 > 解决方案 > peError:只能将str(不是“list”)连接到str

问题描述

我是 python 新手,我收到一条错误消息,只能将 str(不是“列表”)连接到 str 我似乎无法解决问题,请尽快提供反馈,如果你能给我一些帮助,我会非常感激不尽。我尝试循环相同以从列表中选择数字,但它发送以下错误。

这是错误信息

#!/usr/bin/python
import requests
import json
import base64
response1 = requests.get("https://xxx.xxxxxxxx.xxx/oauth/v1/generate?grant_type=client_credentials",
                         auth=('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx','xxxxxxxxxxxxxxxxxx')).text
res=json.loads(response1)
access_token = res['access_token']
api_url = "https://xxx.xxxxxx.xxx/xxxx/stkpush/v1/processrequest"
headers = { "Authorization": "Bearer "+access_token}
timestamp="20210328194700"
shortcode="100100"
passkey="**************************************************8"
def passout(word):
    output=[]
    for each in str(base64.b64encode(bytes(word, 'utf-8'))).split('b\''):
        output.append(each.split("'"))
    return output[1][0]
    
    
password=passout(shortcode+passkey+timestamp)




#amount=100
amount=int(input('enter amount   '))
#mobile=input('enter mobile in format 1XXXXXXXX   ')
#mobile=int(input("Enter number of elements : "))

mobile = ["Geeks\n", "for\n", "Geeks\n"]
 
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(mobile)
file1.close()
 
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
 
count = 0
# Strips the newline character
for line in Lines:
    count += 1
    print


#mobile=[int(x) for x in input().split()]

request ={
      "BusinessShortCode": 100100,
      "Password": password,
      "Timestamp": timestamp,
      "TransactionType": "CustomerPayBillOnline",
      "Amount": 10,
      "PartyA": "1"+mobile,
      "PartyB": 100100,
      "PhoneNumber": "1"+mobile,
      "CallBackURL": "http://demo.health/callback.php",
      "AccountReference": "demo",
      "TransactionDesc": "demo"
    }

response = requests.post(api_url, json = request, headers=headers)

print (response.text)
"""
 Python code to
# demonstrate readlines()
 
L = ["Geeks\n", "for\n", "Geeks\n"]
 
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
 
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
 
count = 0
# Strips the newline character
for line in Lines:
    count += 1
    print("Line{}: {}".format(count, line.strip()))
# demo


The error

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: C:\Users\multiple3.py 
enter amount   10
Traceback (most recent call last):
  File "C:\Users\multiple3.py", line 57, in <module>
    "PartyA": "254"+mobile,
TypeError: can only concatenate str (not "list") to str

标签: python-3.xstringinput

解决方案


实际上,您将listto 变量分配mobile

mobile = ["Geeks\n", "for\n", "Geeks\n"]

并在此处将其与字符串连接起来,如下所示 -

request = {
    ...
    "PartyA": "1" + mobile,
    ...
    "PhoneNumber": "1" + mobile,
    ...
}

推荐阅读