0

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?

2
  • q3 = num * ('?',) Commented Oct 26, 2018 at 10:19
  • 2
    An appeal to all the people who answered below: while responding quickly with an answer is good, just providing a single line of code without explaining or documenting it is a bad practice. The answers here will be read by visitors of this question for years to come. Undocumented solutions doesn't help much if they can't be extended to similar and more complicated problems. Commented Oct 26, 2018 at 10:33

5 Answers 5

2

Try this:

s = '({})'.format(','.join('?' for _ in range(5)))
print(s)

Output

(?,?,?,?,?)

Or:

s = '({})'.format(','.join('?' * 5))

Explanation

  1. The first approach creates a generator using range and join them using ',' finally it surrounds them with parenthesis using the format method.
  2. The second approach is a variation of the first, instead of using a generator expression it creates a string of 5 '?' (i.e. '?????'), as strings are iterables you can use them in join.
Sign up to request clarification or add additional context in comments.

1 Comment

Giving a solution without explaining or documenting it is not a good approach. Try explaining your solution.
1

You can try:

>>> '('+','.join(num*["?"])+')'
'(?,?,?,?,?)'

1 Comment

Giving a solution without explaining or documenting it is not a good approach.
1

Here you go

'(' + ','.join('?'*num) + ')'

Comments

1
print(f"({','.join(['?'] * n)})")

Comments

0

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)})')

Comments

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.