You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python查询MySQL数据库后,如何去除输出结果中的方括号?

Fixing the Bracket in Your MySQL Query Output

Hey there! Let's get rid of those unwanted square brackets in your output. The issue comes down to how you're handling the results from your query:

Why the brackets are showing up

When you use x.fetchall(), each item in the loop is a single-element tuple (like (15000,)). Your map(int, item) call converts this tuple into a list (in Python 2), so when you print it, you see the list's string representation with brackets.

Simple fixes to try

Option 1: Access the tuple's first element directly

Since you're only selecting one column (Amount), each result tuple has exactly one value. Just grab that value directly:

def query(conn): 
    x = conn.cursor() 
    x.execute("SELECT Amount from Expenses") 
    for item in x.fetchall(): 
        # Get the first (and only) element from the tuple
        amount = int(item[0]) 
        print "The amount is %s" % amount

Option 2: Unpack the tuple in the loop

You can also unpack the tuple right in the for loop to make the code cleaner:

def query(conn): 
    x = conn.cursor() 
    x.execute("SELECT Amount from Expenses") 
    # Unpack the single element from each tuple into 'amount'
    for amount, in x.fetchall(): 
        amount = int(amount)
        print "The amount is %s" % amount

Either way, your output will now look like:

The amount is 15000

内容的提问来源于stack exchange,提问作者Bhargav Mg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:05:40