Python中如何去除元组的u'与'符号?现有方案无效求助
Hey there! Let's break down why your current approach isn't working and get you that clean IP address you need.
The Root of the Problem
When you use cursor.fetchall(), it returns a list of tuples—each row in your loop is a single-element tuple like (u'172.1.1.124',). The u'...' is just Python 2's way of indicating a Unicode string, and the parentheses are part of the tuple's syntax. These aren't actual characters in your IP address—they're just how Python displays these data types.
Your previous attempts to convert the tuple to a string/list and use replace() were targeting the string representation of the tuple, not the actual IP value stored inside it. That's why those methods didn't work as expected.
The Simple Fix
Instead of trying to strip characters from the tuple's display, just extract the actual value from the tuple directly. Since each row has exactly one element (your IP), you can access it with row[0]:
sql_cursor = con.cursor() cursor = con.cursor() cursor.execute(get_alerted_ip) Results = cursor.fetchall() for row in Results: # Grab the first (and only) element from the tuple clean_ip = row[0] ip_to_open.append(clean_ip) print(clean_ip) # This will output: 172.1.1.124 con.close()
Extra Notes (For Python 2)
- The
u'...'marker doesn't affect the actual value of the string. If you need a standard ASCII string instead of Unicode, you can convert it withclean_ip.encode('utf-8'), but for most use cases (like passing the IP as a parameter), the Unicode string will work perfectly fine. - If you ever have rows with multiple values, you'd just use
row[1],row[2], etc., to access each column's data.
内容的提问来源于stack exchange,提问作者Tzahi Kadosh

