Reputation: 7644
I have a number.
num = 5
I want to create a pattern of question marks i.e '(?,?,?,....n times)' where n is the number.
in this case the output should be string containing 5 Question marks seperated by comma.
(?,?,?,?,?) #dtype str
I tried it using the below method:
q = '?'
q2 = '('+q
num = 5
for i in range(num-1):
q2 += ','+q
q3 = q2+')'
print(q3)
>>> (?,?,?,?,?)
But it seems very lengthy and naive, is there any pythonic way of doing it? preferably a one liner?
Upvotes: 0
Views: 2161
Reputation: 61910
Try this:
s = '({})'.format(','.join('?' for _ in range(5)))
print(s)
Output
(?,?,?,?,?)
Or:
s = '({})'.format(','.join('?' * 5))
Explanation
','
finally it surrounds them with parenthesis using the format method.'?'
(i.e. '?????'
), as strings are iterables you can use them in join.Upvotes: 2
Reputation: 1063
I would assemble the string using f-string syntax, as it allows to use a higher level abstraction after the more basic logic is sorted out:
q = '?'
n = 5
s = ",".join(q*n) # You get a string without parenthesis: '?,?,?,?,?'
print(f'({s})') # Here you are adding the parenthesis
There are several ways to do it. In the end, it all comes to readability and, sometimes, performance. Both F-strings and .join()
tend to be efficient ways to build strings.
You cam merge it into a one-liner if you want it:
q = '?'
n = 5
print(f'({",".join(q*n)})')
Upvotes: 0
Reputation: 31161
You can try:
>>> '('+','.join(num*["?"])+')'
'(?,?,?,?,?)'
Upvotes: 1