Как вставить переменную в строку в Python?
Чтобы вставить переменные в строку в Python, мы можем использовать форматированные строковые литералы.
Поместите символ f перед началом строкового литерала с одинарными или двойными кавычками, как показано ниже.
Теперь мы можем ссылаться на переменные внутри этой строки. Все, что нам нужно сделать, это заключить переменные в фигурные скобки <переменная>и поместить ее внутри строкового значения, где это необходимо. Пример приведен ниже.
В приведенной выше программе у нас есть переменная с именем var1, и мы вставили эту переменную в строку, используя форматированные строки.
Пример 1
В этом примере мы возьмем целые числа в переменных и попытаемся вставить несколько переменных внутри строки, используя форматированную строку.
Пример 2
В этом примере мы возьмем строковые литералы в переменных и попытаемся добавить их внутри строки, используя форматированную строку.
В этом руководстве на примерах Python мы узнали, как помещать переменные в строковый литерал с помощью примеров программ.
How do I put a variable’s value inside a string (interpolate it into the string)?
I would like to put an int into a string . This is what I am doing at the moment:
I have to run the program for several different numbers, so I’d like to do a loop. But inserting the variable like this doesn’t work:
How do I insert a variable into a Python string?
See also
If you are trying to create a file path, see How can I create a full path to a file from parts (e.g. path to the folder, name and extension)? for additional techniques. It will usually be better to use code that is specific to creating paths.
If you are trying to assemble a URL with variable data, do not use ordinary string formatting, because it is error-prone and more difficult than necessary. Specialized tools are available. See Add params to given URL in Python.
If you are trying to assemble a SQL query, do not use ordinary string formatting, because it is a major security risk. This is the cause of "SQL injection" which costs real companies huge amounts of money every year. See for example How to use variables in SQL statement in Python? for proper techniques.
If you just want to print (output) the string, you can prepare it this way first, or if you don’t need the string for anything else, print each piece of the output individually using a single call to print . See How can I print multiple things (fixed text and/or variable values) on the same line, all at once? for details on both approaches.
9 Answers 9
This was added in 3.6 and is the new preferred way.
Using local variable names (neat trick):
![]()
With the introduction of formatted string literals («f-strings» for short) in Python 3.6, it is now possible to write this with a briefer syntax:
With the example given in the question, it would look like this
![]()
The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:
![]()
You can use + as the normal string concatenation function as well as str() .
![]()
In general, you can create strings using:
![]()
If you would want to put multiple values into the string you could make use of format
Would result in the string hanning123.pdf . This can be done with any array.
Special cases
Depending on why variable data is being used with strings, the general-purpose approaches may not be appropriate.
If you need to prepare an SQL query
Do not use any of the usual techniques for assembling a string. Instead, use your SQL library’s functionality for parameterized queries.
A query is code, so it should not be thought about like normal text. Using the library will make sure that any inserted text is properly escaped. If any part of the query could possibly come from outside the program in any way, that is an opportunity for a malevolent user to perform SQL injection. This is widely considered one of the important computer security problems, costing real companies huge amounts of money every year and causing problems for countless customers. Even if you think you know the data is "safe", there is no real upside to using any other approach.
The syntax will depend on the library you are using and is outside the scope of this answer.
If you need to prepare a URL query string
See Add params to given URL in Python. Do not do it yourself; there is no practical reason to make your life harder.
Writing to a file
While it’s possible to prepare a string ahead of time, it may be simpler and more memory efficient to just write each piece of data with a separate .write call. Of course, non-strings will still need to be converted to string before writing, which may complicate the code. There is not a one-size-fits-all answer here, but choosing badly will generally not matter very much.
If you are simply calling print
The built-in print function accepts a variable number of arguments, and can take in any object and stringify it using str . Before trying string formatting, consider whether simply passing multiple arguments will do what you want. (You can also use the sep keyword argument to control spacing between the arguments.)
Of course, there may be other reasons why it is useful for the program to assemble a string; so by all means do so where appropriate.
It’s important to note that print is a special case. The only functions that work this way are ones that are explicitly written to work this way. For ordinary functions and methods, like input , or the savefig method of Matplotlib plots, we need to prepare a string ourselves.
Concatenation
Python supports using + between two strings, but not between strings and other types. To work around this, we need to convert other values to string explicitly: ‘hanning’ + str(num) + ‘.pdf’ .
Template-based approaches
Most ways to solve the problem involve having some kind of "template" string that includes "placeholders" that show where information should be added, and then using some function or method to add the missing information.
f-strings
This is the recommended approach when possible. It looks like f’hanning
Because it’s a special syntax, it can access opcodes that aren’t used in other approaches.
str.format
This is the recommended approach when f-strings aren’t possible — mainly, because the template string needs to be prepared ahead of time and filled in later. It looks like ‘hanning<>.pdf’.format(num) , or ‘hanning
Particularly for str.format , it’s useful to know that the built-in locals , globals and vars functions return dictionaries that map variable names to the contents of those variables. Thus, rather than something like ‘
str.format_map
This is a rare variation on .format . It looks like ‘hanning
That probably doesn’t sound very useful — after all, rather than ‘hanning
string.Formatter
The string standard library module contains a rarely used Formatter class. Using it looks like string.Formatter().format(‘hanning
All of the above approaches use a common "formatting language" (although string.Formatter allows changing it); there are many other things that can be put inside the <> . Explaining how it works is beyond the scope of this answer; please consult the documentation. Do keep in mind that literal < and >characters need to be escaped by doubling them up. The syntax is presumably inspired by C#.
The % operator
This is a legacy way to solve the problem, inspired by C and C++. It has been discouraged for a long time, but is still supported. It looks like ‘hanning%s.pdf’ % num , for simple cases. As you’d expect, literal ‘%’ symbols in the template need to be doubled up to escape them.
It has some issues:
It seems like the conversion specifier (the letter after the % ) should match the type of whatever is being interpolated, but that’s not actually the case. Instead, the value is converted to the specified type, and then to string from there. This isn’t normally necessary; converting directly to string works most of the time, and converting to other types first doesn’t help most of the rest of the time. So ‘s’ is almost always used (unless you want the repr of the value, using ‘r’ ). Despite that, the conversion specifier is a mandatory part of the syntax.
Tuples are handled specially: passing a tuple on the right-hand side is the way to provide multiple arguments. This is an ugly special case that’s necessary because we aren’t using function-call syntax. As a result, if you actually want to format a tuple into a single placeholder, it must be wrapped in a 1-tuple.
Other sequence types are not handled specially, and the different behaviour can be a gotcha.
string.Template
The string standard library module contains a rarely used Template class. Instances provide substitute and safe_substitute methods that work similarly to the built-in .format ( safe_substitute will leave placeholders intact rather than raising an exception when the arguments don’t match). This should also be considered a legacy approach to the problem.
Inserting values into strings¶
You can use the string method format method to create new strings with inserted values. This method works for all current releases of Python. Here we insert a string into another string:
The curly braces show where the inserted value should go.
You can insert more than one value. The values do not have to be strings, they can be numbers and other Python objects.
You can do more complex formatting of numbers and strings using formatting options within the curly brackets — see the documentation on curly brace string formatting.
This system allows us to give formatting instructions for things like numbers, by using a : inside the curly braces, followed by the formatting instructions. Here we ask to print in integer ( d ) where the number should be prepended with 0 to fill up the field width of 3 :
This prints a floating point value ( f ) with exactly 4 digits after the decimal point:
See the Python string formatting documentation for more details and examples.
Option 2 — f-strings in Python >= 3.6¶
If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable names within the string. For example, here is an example like the one above, using the f-string syntax:
Option 3 — old school % formatting¶
There is an older method of string formatting that uses the % operator. It is a bit less flexible than the other two options, but you will still see it in use in older code, and where using % formatting is more concise.
For % operator formating, you show where the inserted values should go using a % character followed by a format specifier, to say how the value should be inserted.
Here is the example above, using % formatting. Notice the %s marker to insert a string, and the %d marker to insert an integer.
Как подставить данные в строку в Python? Что такое форматирование строк?

Python использует форматирование строк в стиле C для создания новых форматированных строк. Оператор «%» используется для форматирования набора переменных, заключенных в «кортеж» (список фиксированного размера), вместе со строкой форматирования, которая содержит обычный текст вместе с «спецификаторами аргумента», специальными символами, такими как %s и %d .
Допустим, у вас есть переменная с именем «name» с вашим именем пользователя, и вы хотели бы затем вывести (приветствие этому пользователю).
Чтобы использовать два или более спецификатора аргумента, используйте кортеж (круглые скобки):
Любой объект, который не является строкой, также может быть отформатирован с использованием оператора % s. Строка, которая возвращается из метода «repr» этого объекта, форматируется как строка. Например:
Вот некоторые основные спецификаторы аргументов, которые вы должны знать:
%s — String (or any object with a string representation, like numbers)
%f — Floating point numbers
%.<number of digits>f — Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X — Integers in hex representation (lowercase/uppercase)
Упражнение
Вам нужно будет написать строку формата, которая выводит данные, используя следующий синтаксис: Hello John Doe. Your current balance is $53.44.