Shubham R
Shubham R

Reputation: 7644

Create a pattern of string in python

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

Answers (5)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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.

Upvotes: 2

Victor Domingos
Victor Domingos

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

Silver
Silver

Reputation: 1468

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

Upvotes: 1

hspandher
hspandher

Reputation: 16733

Here you go

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

Upvotes: 1

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can try:

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

Upvotes: 1

Related Questions