如何在Python中拆分字符串?以提取坐标1403,1500为x、y为例
Python字符串拆分实现坐标提取
针对格式为'1403,1500'的坐标字符串,我们可以通过逗号拆分+类型转换的方式提取x、y坐标,以下是完善后的代码:
def get_coord(self): try: coords = make_tuple(driver.find_element(By.XPATH,'/html/body/div[3]/div[4]').text) # 拆分并转换为整数坐标 x_coord = int(coords[0]) y_coord = int(coords[1]) return x_coord, y_coord except: # 异常时返回空坐标,可根据需求调整处理逻辑 return None, None
关键逻辑说明:
- 假设
make_tuple函数会将获取到的文本(如'1403,1500')转换为包含两个元素的元组(如('1403', '1500')),直接通过索引提取对应值 - 用
int()将字符串类型的坐标值转换为整数,满足数值计算需求 - 如果
make_tuple未做拆分处理,可直接替换为字符串拆分逻辑:coord_text = driver.find_element(By.XPATH,'/html/body/div[3]/div[4]').text x_str, y_str = coord_text.split(',') x_coord = int(x_str) y_coord = int(y_str) - 建议将裸
except改为捕获特定异常(如NoSuchElementException、ValueError),避免隐藏非预期错误
内容的提问来源于stack exchange,提问作者Bayxlarge
相关产品推荐
相关产品推荐

