0

how do i add a digit to an integer in python ?

value = 9

#add a 9 to "value" to get 99

print(value)

So i want the console to return :

99

I tryed to do

value.append(9)

but it didnt work

2
  • 2
    Yes, you have to use math. What number would you add to 9 to get 99? Commented Nov 1, 2022 at 20:51
  • 1
    Multiply it by 10, then add the new digit value. For example, if you have 123 and want to add 6 to the end, you can use 10*123 + 6 to get 1236. It's just arithmetic. Commented Nov 1, 2022 at 20:52

2 Answers 2

1

I think you could convert your number to a string, add those together, and then convert it back into an integer. Something like

var1 = "9" var2 = var1 + var1 convertedAnswer = int(var2) print(convertedAnswer)

could work?

Sign up to request clarification or add additional context in comments.

1 Comment

Tysm ! It worked !
0

You can convert int to str, concatenate the strings, and the convert back to int:

value = 9

add = 9

print(int(str(value) + str(add)))

4 Comments

Shortest solution: print(int(f"{value}{add}")) @Tom Sometimes it is not worth complicating the matter and using the simplest solution.
@TomKarzes meh, I'd say profile it before calling it "rediculous".
@TomKarzes maybe you're right. but think if you have to add an integer instead of a digit, the solution wouldn't look so ridiculous (btw that is what I was thinking for some reason when proposing this)
@TomKarzes well, 10*123+6 will just result in a bytecode for retrieving a constant. You want something like: timeit.timeit("10*x+y", setup="x=123; y=6") which gives me 0.07322674599999957 and compare that to: timeit.timeit('int(f"{x}{y}")', setup="x=123; y=6") which gives me 0.29948458500000186 so about a 4X speedup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.