Reputation: 71
I need to define a function which repeats a number 3 times. I can only get it to work as a list where the output is [1, 1, 1] if the input is 1. However I need the output to be 111 This is what I have
def repeat_number(num):
if not type(num) is int:
return None
list_1 = []
x = list_1.append(num)
y = list_1*3
for i in y:
return i,i,i
a = 12
print (repeat_number(a))
and again I want the output to be 121212
Upvotes: 0
Views: 2213
Reputation: 1282
You can cast the number as a string and multiply.
def repeat(num):
return str(num)*3
a = 12
print(repeat(a))
Upvotes: 0
Reputation: 49318
If the output is [1, 1, 1]
and you were looking for 111
, you can do the following:
print (*repeat_number(a), sep='')
However, I'd recommend doing the following with your function:
def repeat_number(num):
if type(num) != int: return
return int(str(num)*3)
And then all you have to do is:
print (repeat_number(a))
as you originally attempted. Plus, this function returns an actual number, which is probably good.
Upvotes: 0
Reputation: 31339
You can use a simple str.join
for this, and create a general function:
def repeat(something, times, separator):
return separator.join([str(something) for _ in range(times)])
And now use it to create your specific function:
def repeat_three_times(something):
return repeat(something, 3, '')
Output:
>>> repeat_three_times(1)
'111'
Few things to note:
str
to cast the expected integer to a stringstr.join
expectsstr.join
to create a string which is a concatenation of the strings in the list (see 2).Here is an example of using the more general function in a different way:
>>> repeat(1, 4, ',')
'1,1,1,1'
Upvotes: 1