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
相关产品推荐
相关产品推荐

