Arif
Arif

Reputation: 49

How to replace string that contains curly bracket in Python?

Please see below code to understand my problem:

str_line = data['line']  # data['line'] holds "I was born in {year}"
str_year = '1987'

Expected output: I was born in 1987

print(str_line)

I have tried using following methods but the output always the original str_line (i.e., I was born in {year}).

str_line = str_line.replace('{{year}}',str_year)

and

str_line = str_line.replace('/{year/}',str_year)

Upvotes: 3

Views: 2007

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You can use str.format() with year argument set to str_year:

str_line = "I was born in {year}"
str_year = '1987'
print( str_line.format(year=str_year) )
# => I was born in 1987

See the Python demo online

Documentation says

str.format(*args, **kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

Upvotes: 1

Related Questions