簡體   English   中英

無法將字符串放入列表(錯誤消息)

[英]Having Trouble Putting Strings into a List (error message)

我想使用以下代碼:

for x in story:
    var1 = str(x)
    var1 = var1.replace("<p>", "\n")
    var1 = var1.replace("</p>", "")
    story[x] = var1

刪除段落標記,插入換行符,然后將它們重新插入變量中。 字符串如下:

Panera Bread (NASDAQ: <a class="ticker" href="/stock/pnra#NASDAQ">PNRA</a>) is down 6 percent today over expectations of food inflation of 4.5% in Q3 and 5% for Q4. In addition, Panera Will Raise Menu Prices in Q4.

PNRA recently posted second quarter 2011 earnings of $1.18 per share. Reported earnings also outpaced the prior-year quarter earnings of 85 cents per share. 

But shares were also lower ahead of the opening bell after the company reported weaker-than-expected same-store sales figures for its recent quarter late Tuesday. Its profit of $1.18 a share topped analysts' consensus call by a penny.

For the twenty-six weeks ended June 28, 2011, net income was $68 million, or $2.27 per diluted share. These results compare to net income of $53 million, or $1.67 per diluted share, for the twenty-six weeks ended June 29, 2010, and represent a 36% year-over-year increase in diluted earnings per share.

我得到的錯誤消息是:

Traceback (most recent call last):
  File "C:\Python27\Sample Programs\Get Stuff from Pages\Pages and Stuff 0.1.py", line 34, in <module>
    story[x] = var1
TypeError: list indices must be integers, not Tag

for循環迭代地將列表story元素替換為x變量,而[] list指令需要元素索引。 這導致錯誤。

l = ['a','b']
print l[0]
print l['a'] // type error

編輯 :我錯過了那個故事不包含字符串。 這種變化可以完成這項工作:

story = [str(x).replace("<p>","\n").replace("<\p>","") for x in story]

注意 :現在story由字符串組成,而不是標簽。

您可能希望將項目附加到列表中:

story.append(var1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM