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

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 (with statement): 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:34:05