You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:15:56