dkentre
dkentre

Reputation: 289

How to append to the beginning of an int in Python?

First of all, is it possible to append to an int ? If not I guess i'll have to convert it to a string first. I know how to append to a list Anyways, how would you append a digit to the beginning of a number(instead of appending it to the end). Say number = 345, and you'd like to append super which is equal to 2 to the beginning of "number" to make it "2345". How would you do it ? To append it to the end of a list i'd use:

alist.append("hello")

Upvotes: 0

Views: 1735

Answers (2)

Shashank
Shashank

Reputation: 13869

To "append" to numbers, you need to convert them to strings first with str(). Numbers are immutable objects in Python. Strings are not mutable either but they have an easy-to-use interface which makes it easy to create modified copies of them.

number = 345
new_number = int('2' + str(number))

Once you are done editing your string, you can easily convert it back to an int with int().

Note that strings don't have an append method like lists do. You can easily concatenate strings with the + operator however.

Upvotes: 2

miku
miku

Reputation: 188034

As @Fredrik comments, you can get from any integer to any other integer by a single addition - and this is how you should probably do it, if you deal with integers only.

>>> i = 345
>>> 2000 + i
2345

There are, however, many way to express "prepend a 2 to 345", one would be to use format:

>>> '2{}'.format(345)
'2345'

Upvotes: 1

Related Questions