Reputation: 1416
I have a range 10-20 and I want to add a 0 in between each digit, so for example:
range(10,15) returns 10, 11, 12, 13, 14
I want it to loop through and return 1000, 1010, 1020, 1030 and 1040.
I tried this:
a = range(10,20)
for i in a:
i.append(0)
print (i)
No luck. Error message says:
i.append(0)
AttributeError: 'int' object has no attribute 'append'
What am I doing wrong? Thanks.
Upvotes: 0
Views: 217
Reputation: 2041
This task can be solved either using strings (the 0's are being implicitly appended here) or by keeping this problem in the integer domain. Build either approach as a function and then use a list comprehension or built-in map
to add 0's to every item in your range.
Option 1: convert to string, add 0's, convert back to integer
int(''.join((s+'0' for s in str(13)))
Option 2: stay in integer domain
result = 0
digit = 0
num = 14
while num>1:
result += 10**(2*digit) * (num % 10)
num //= 10 # integer division
digit += 1
return result
By any chance were you looking for range(1000, 1050, 10)
, which gives the values 1000, 1010, 1020, 1030, 1040
?
Upvotes: 1
Reputation: 1758
As Tim Pietczker mentioned in his comment (which is much more an answer), you don't need to stuck with ranges of one increment. You can simply:
a = range(1000,2000,10)
However, your original code can be fixed like this:
a = range(10,20)
for i in a:
si=str(i) # convert your i integer to si string
newsi='' # initalize a new empty string
for letter in si: # loop through your string of digits
newsi+=letter # add the oncoming digit to the new string
newsi+=0 # add a 0 to the new string
newi=int(newsi) # convert your new string to integer
print newi
Upvotes: 1
Reputation: 9904
You are trying to add strings to a number which you can't. You should first convert the number to a string.
[int('0'.join(str(i))+'0') for i in range(10, 20)]
Upvotes: 4