Python 3.6 - интерполяция буквенных строк с использованием JSON - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь прочитать файл JSON, который включает Python переменные, которые должны отображаться как значение переменной, а не как сама переменная.

with open('path_to_file.json') as f:
           my_json = json.load(f)

json_variable = my_json['text']

# The example text in the json file is:
# Hello, I want to be there in {defined_days} days

defined_days = 3

# What I tried, but doesn't work
interpolated_text = f'{json_variable}'

# Output of interpolated_text:
# Hello, I want to be there in {defined_days} days

Показывает Строка из файла json, но fined_days не будет заменена на число 3 .

1 Ответ

0 голосов
/ 26 марта 2020

Поскольку ваша строка формата находится в переменной, вам нужно использовать метод format вместо f-строк

json_variable = 'Hello, I want to be there in {defined_days} days'

defined_days = 3

interpolated_text = json_variable.format(**locals())

print(interpolated_text)

Вывод:

Hello, I want to be there in 3 days
...