如何在python上把碎片做成字符串



如何将14031500这样的字符串分割为x,y

def get_coord(self):
    try:
        coords = make_tuple(driver.find_element(By.XPATH,'/html/body/div[3]/div[4]').text)
        x_coord = 
        y_coord = 
    except:
         pass

在python中,您可以解压缩可迭代对象,如dicts、元组、列表或字符串。您可以将元组值分配给如下变量:

coords = (1, 2)
x, y = coords 
print(x, y)
>>> 1, 2

因此您有以下字符串

coords = "1403,1500"

您希望将数字提取为字符串,然后将其转换为整数。

# Extract strings separated by ","
strings = coords.split(",")
# Convert to integer
x = int(strings[0])
# But it might fail, so you might want to handle the Exception
try:
    x = int(strings[0])
except ValueError:
    x = None  # Or whatever behavior you want

# Then all in one without handling the exception :
def extract_coord(coords: str) -> (int, int):
    return tuple(map(int, coords.split(",")))
x, y = extract_coord("123,456")
print(f"{x = } ; {y = }")

最新更新