pythonstring

Is there a way to increase numeric value in a string variable? [Python]


I'm trying some web-scraping which requires to loop through some elements having attribute in a string format. But the string is a numeric value which increases throughout the element.

data_id="1"

Is there a way to increase the value of data-id to "2" to "3" so on while it remains in string format?


Solution

  • First, convert the string to an integer, you can do that with the int builtin:

    int(data_id)

    Then add 1 to that integer:

    int(data_id) + 1

    Finally, convert the new integer back to a string, you can do that with the str builtin:

    str(int(data_id) + 1)

    E.g.

    >>> data_id = "1"
    >>> data_id = str(int(data_id) + 1)
    >>> data_id
    '2'