去除以列表中未包含的字符开头的所有内容
Stripping everything starting with character not included in list
使用代码:
from lxml import html
import requests
tree = html.fromstring(requests.get('http://selectshop.pl/deskorolka-blaty-decki,40/1').content)
print [elem.encode('utf8').replace(',','.') for elem in tree.xpath('//span[@class="price"]/text()')]
我正在获取像 '189.00 z\xc5\x82'
这样的字符串列表。
我想从列表的每个元素中删除 z\xc5\x82
部分。我可以使用 .strip(' z\xc5\x82')
但我宁愿删除从第一个字符开始(从左开始)不在列表 ['0','1','2','3','4','5','6','7','8','9','.']
中的所有内容
因为在某些情况下要删除的字符串可能会有所不同。如何做到这一点?
您可以使用 regex,例如:
import re
s = "189.00 z\xc5\x82"
s = re.sub(r"[^\d.]", "", s)
print(s) # prints "189.00"
因此您需要更改此部分:
elem.encode('utf8').replace(',','.')
进入:
re.sub(r"[^\d.]", "", elem.encode('utf8').replace(',','.'))
使用 str.isdigit
with generator expression to filter only digits and dots, then str.join
将过滤后的字符连接回字符串:
>>> ''.join(c for c in '189.00 z\xc5\x82' if c.isdigit() or c == '.')
'189.00'
>>> allowed_chars = set(['0','1','2','3','4','5','6','7','8','9','.'])
# OR allowed_chars = set('0123456789.')
>>> ''.join(c for c in '189.00 z\xc5\x82' if c in allowed_chars)
'189.00'
使用代码:
from lxml import html
import requests
tree = html.fromstring(requests.get('http://selectshop.pl/deskorolka-blaty-decki,40/1').content)
print [elem.encode('utf8').replace(',','.') for elem in tree.xpath('//span[@class="price"]/text()')]
我正在获取像 '189.00 z\xc5\x82'
这样的字符串列表。
我想从列表的每个元素中删除 z\xc5\x82
部分。我可以使用 .strip(' z\xc5\x82')
但我宁愿删除从第一个字符开始(从左开始)不在列表 ['0','1','2','3','4','5','6','7','8','9','.']
中的所有内容
因为在某些情况下要删除的字符串可能会有所不同。如何做到这一点?
您可以使用 regex,例如:
import re
s = "189.00 z\xc5\x82"
s = re.sub(r"[^\d.]", "", s)
print(s) # prints "189.00"
因此您需要更改此部分:
elem.encode('utf8').replace(',','.')
进入:
re.sub(r"[^\d.]", "", elem.encode('utf8').replace(',','.'))
使用 str.isdigit
with generator expression to filter only digits and dots, then str.join
将过滤后的字符连接回字符串:
>>> ''.join(c for c in '189.00 z\xc5\x82' if c.isdigit() or c == '.')
'189.00'
>>> allowed_chars = set(['0','1','2','3','4','5','6','7','8','9','.'])
# OR allowed_chars = set('0123456789.')
>>> ''.join(c for c in '189.00 z\xc5\x82' if c in allowed_chars)
'189.00'