[英]concatenating a string with elements of list returns only the last element
我正在使用BeutifulSoup從html文件中提取某些數據,當我應用以下代碼作為最終結果時,即標記子級列表的所有元素的連接,我僅在歌詞中得到了final元素。變量。
lyrics = ""
for content in songResult.children:
if "br" in str(content):
continue
lyrics += str(content)
print(lyrics)
子級是br標簽或songResult標簽中的文本。 我忽略了br標簽,並嘗試使用print(content)
而不是lyrics += str(content)
然后打印效果完美。 我似乎無法找出問題的根源。 有什么建議嗎?
對我來說很好。 我做了:
lyrics = ""
children = ['testbr', 'test', 'testbr2', 'test', 'testbr3']
for content in children:
if "br" in str(content):
continue
lyrics += str(content)
print('in loop'),
print(lyrics)
print('out of loop'),
print(lyrics)
上面的代碼段對您有用嗎?
確保此代碼不在另一個循環中,以使“歌詞”未重置為“”。 這將導致您描述的症狀(在if語句中打印出來很好,但是“歌詞”僅包含最后一個變量)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.