如何在Python中从Worksheet对象列表中提取仅工作表名称?
Got it, let's tackle how to pull just the worksheet names from your list of Worksheet objects in Python. Here's what you need to know:
The Reliable, Preferred Method: Access the Worksheet's title Attribute
Most spreadsheet libraries (like gspread for Google Sheets, or openpyxl for Excel) equip Worksheet objects with a direct title attribute that stores the sheet name. This is way more reliable than parsing the object's string representation since it uses the object's native property.
Example Code
First, let's replicate your sample data to test with:
# Mock Worksheet class to simulate your actual Worksheet objects class MockWorksheet: def __init__(self, title, sheet_id): self.title = title self.id = sheet_id def __repr__(self): return f"<Worksheet '{self.title}' id:{self.id}>" # Your input list of Worksheet objects worksheet_list = [ MockWorksheet('Publisher List Approval', 0), MockWorksheet('Live Links (Jan-March)', 2076026864), MockWorksheet('Live Links (April, May, June)', 1550372032), MockWorksheet('Live Links (Q3: July-Sept)', 937560092) ]
Now extract the names with a clean list comprehension:
# Extract all worksheet titles in one line worksheet_names = [ws.title for ws in worksheet_list] # Print the result print(worksheet_names)
Output
['Publisher List Approval', 'Live Links (Jan-March)', 'Live Links (April, May, June)', 'Live Links (Q3: July-Sept)']
Fallback: Parse the String Representation (Only If Necessary)
If for some edge case you can't access the title attribute (this is rare with well-maintained libraries), you can parse the string output of the Worksheet objects using regex. Heads up: This is fragile—if the object's string format changes later, this code will break.
Code for Fallback Method
import re # Extract names by parsing the object's string representation worksheet_names_regex = [re.search(r"'(.*?)'", str(ws)).group(1) for ws in worksheet_list] print(worksheet_names_regex)
This regex targets the text wrapped in single quotes in the object's string, which corresponds to the sheet name in your sample data.
内容的提问来源于stack exchange,提问作者Aibak

