我试图用xpath
的空白分割字符串,但它不起作用
x="78646182309549(5)"
x.split()
所以我用
检查字符串上是否有空白x.isspace()
返回False
Html:
<td class="tl"><a href="https://www.zto.com/?num=78646182309549(5)" target="_blank" style="font-weight:bold;font-size:14px;">78646182309549(5)</a></td>
x = response.xpath("(//td[@class='tl']//a)[1]/text()").extract_first()
print(x)
print(x.isspace())
所需输出:
x = ['78646182309549','(5)']
y = x[0]
print(y)
78646182309549
isspace()方法如果字符串中的所有字符都是空格则返回True,否则返回False。
严格来说,x:
中没有空格[y for y in x]
['7', '8', '6', '4', '6', '1', '8', '2', '3', '0', '9', '5', '4', '9', '(', '5', ')']
:
"78646182309549(5)".split()
的回报:
['78646182309549(5)']
你可以这样分割:
x="78646182309549(5)".split('(')
#output ['78646182309549', '5)']
x[0]='78646182309549'
如果所有字符串为空格,则isspace()
返回True
' '.isspace() # True
和按空格分隔需要使用
split(' ')
但是这在这里没有帮助,因为(
是文本中的单个字符。使用re.split
x = "78646182309549(5)"
x = re.split(r'(()', x)
x1, x2 = x[0], ''.join(x[1:])
# or
x = [x[0], ''.join(x[1:])]
print(x[0]) # 78646182309549
print(x[1]) # (5)
编辑按照@mozway的建议,你可以做
x = "78646182309549(5)"
x = re.split(r'(?=()', x)
print(x) # ['78646182309549', '(5)']