为什么不能将lxml.etree._ElementUnicodeResult转换为字符串? [英] Why can't I cast an lxml.etree._ElementUnicodeResult to a string?

查看:251
本文介绍了为什么不能将lxml.etree._ElementUnicodeResult转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print(type(players[1]))


for player in players:
    player = str(player)

print(type(players[1]))

输出为:

 <class 'lxml.etree._ElementUnicodeResult'>
 <class 'lxml.etree._ElementUnicodeResult'>

我需要将此ElementUnicode对象转换为字符串,以便可以在其上调用子字符串,但是此for循环没有执行此操作.当我将其强制转换为字符串并同时调用子字符串时,控制台将读取:str对象没有对象子字符串,这没有任何意义.

I need to convert this ElementUnicode object into a string so that I can call substring on it, but this for loop isn't doing it. And when I cast it to a string and call substring at the same time, the console reads: str object has no object substring, which makes no sense.

 str(players[i]).substring()

有什么想法可能会导致这种情况,以及如何解决在此对象上调用子字符串的问题?

Any thoughts on why that may be the case and how I could get around to calling substring on this object?

推荐答案

_ElementUnicodeResult 投射到 str 并不是问题.完整的演示:

Casting _ElementUnicodeResult to str is not a problem. Complete demonstration:

from lxml import etree

doc = """
<root>
 <player>ABC</player>
 <player>DEF</player>
</root>"""

root = etree.fromstring(doc)
players = root.xpath("player/text()")

print(type(players[1]))

# Cast each player to a plain string 
players = [str(p) for p in players]

print(type(players[1]))

输出:

<class 'lxml.etree._ElementUnicodeResult'>
<class 'str'>


在问题中,您具有以下代码:


In the question, you have the following code:

for player in players:
    player = str(player)

print(type(players[1]))

这不会更改 for 循环之外的任何内容. type(players [1])与以前相同.

This does not change anything outside the for loop. type(players[1]) will be the same as before.

此外,确实是 str 没有 substring 属性.XPath具有 substring()函数.也许这就是您的想法?

In addition, it is true that str has no substring attribute. XPath has a substring() function. Maybe that is what you were thinking of?

这篇关于为什么不能将lxml.etree._ElementUnicodeResult转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆