Python读取tickers.txt文件后如何将行情代码格式化为指定的列表字符串形式?
Solution to Format Tickers into List String
Here's a straightforward, robust way to get your desired output format, including best practices for file handling:
First, let's adjust your code to properly process the tickers and convert them into the list format you want:
# Use a context manager to safely read the file (automatically closes it afterward) with open("tickers.txt", "r") as fh: # Read the entire content and strip any leading/trailing whitespace (like newlines) tickers_raw = fh.read().strip() # Split the raw string by commas, then clean up each ticker # The list comprehension removes empty entries (from trailing commas) and extra spaces tickers_list = [ticker.strip() for ticker in tickers_raw.split(",") if ticker.strip()] # Print the list—this will output exactly the format you need! print(tickers_list)
Breakdown of how this works:
- Context Manager (
withstatement): This is better practice than manually opening/closing files because it ensures the file is closed properly even if an error occurs, preventing resource leaks. - Stripping Whitespace:
fh.read().strip()removes any extra newlines or spaces at the start/end of the file content, which avoids unexpected empty entries later. - Splitting and Cleaning: Splitting on
","handles cases where there might be inconsistent spacing (or a trailing comma in your input). The list comprehension then strips whitespace from each ticker and filters out any empty strings that result from trailing commas. - Printing the List: When you print a Python list of strings, it automatically outputs in the
["ticker1", "ticker2", ...]format you're looking for.
If you specifically need a string version of this list (instead of the list object itself), you can convert it using str(tickers_list), but printing the list directly should give you exactly the output you need.
内容的提问来源于stack exchange,提问作者M4Biz
相关产品推荐
相关产品推荐

