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

Viewed 110

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?

4 Answers

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'

I will just explain the response In the comment of @rdas and @Jax Teller code:

    1. First, you convert your string to integer value, for this we use int(my_string), let assume, you store the result in a variable called int_val like int_val = int(my_string),
    1. Then you increase you integer value int_val = int_val + 1,
    1. At the end you convert back the result to string using str(...) : my_str=str(int_val).
my_string = "1"
int_val = int(my_string)
int_val = int_val + 1
my_string = str(int_val)

These steps are compacted in one single line like my_str = str(int(my_str)+1). Good luck.

something like the below

def increment_str(string):
    return str(int(string) + 1)


print(increment_str("12"))

output

13

I would recommend to use an integer variable in the first place and convert it to a string as needed:

data_id = 1

fetch_element_(data_id=str(data_id))

data_id += 1

fetch_element_(data_id=str(data_id))

Now, you can simplify that code using a for-loop and the built-in range function:

for data_id in range(1,4):  # This will loop through the numbers [1, 2, 3]
    fetch_element_(data_id=str(data_id))

When your first id is given as a string in the beginning, you can use the int constructor to convert it to an int, as suggested in the other answers:

data_id = int("1")  # or int(some_string_variable)
Related