1

It's a simple question. I have a generic string and I want to replace an asterisk * with arguments provided.

'* is the capital of *'

If I shall give two arguments ('Berlin','Germany'), I should get

'Berlin is the capital of Germany'

It's an easy problem, and I can solve it, but I am looking for one line solution where every positional argument replaces the corresponding *. I think, I have seen something of this type (*) ...(*), but can't recollect. Someone has any idea?

3 Answers 3

2

You have many ways to do this, a simple one if you have tuples of 2 elements:

t = ('Berlin', 'Germany')
'{} is the capital of {}'.format(*t)

or

'%s is the capital of %s' % t

output: 'Berlin is the capital of Germany'

Sign up to request clarification or add additional context in comments.

Comments

1

You could use an f-String like this:

city = "Berlin"
country = "Germany"
print(f"{city} is the capital of {country}")

Basically, you're no longer using arguments and formatting, you're putting the python code directly into the string.

Comments

0

If you replace the '*' with '{}', you can use the format method:

s = '* is the capital of *'
replacement = ['Berlin', 'Germany']
print(s.replace('*', '{}').format(*replacement))

1 Comment

Thanks for your answer. I wanted to avoid replace all together.

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.