- Как подставить переменную в строку
- Как не надо
- .format cо строковыми литералами
- Сложение
- replace
- Как ещё можно
- Попробуйте бесплатные уроки по Python
- How to put a variable inside a string in Python?
- Put a variable inside a string using f-string
- Frequently Asked:
- Put a variable inside a string using format() method
- Put a variable inside a string using String Concatenation
- Put a variable inside a string using % Operator
- Summary
- Related posts:
- Python: Add Variable to String & Print Using 4 Methods
- Method #1: using String concatenation
- Method #2: using the «%» operator
- Method #3: using the format() function
- Method #4: using f-string
- Conclusion
- Related Tutorials:
- How to place Variables in String in Python?
- Examples
- 1. Write variables in strings
- 2. Format string values in a given string
- Summary
- Quiz on
Как подставить переменную в строку
В Python есть шесть способов подставить переменную в строку. Не все из них социально приемлемые. Если коротко, то преподаватель точно не завернёт работу, использующую .format :
person1 = 'Александра' person2 = 'Александр' message_template = """Здравствуйте, ! На связи . . С уважением, """ message = message_template.format(recipient=person1, sender=person2) print(message)
Как не надо
.format cо строковыми литералами
Выносить в параметры .format нужно только изменяющиеся данные. Не стоит писать
message_template = " " message = message_template.format( greeting='Здравствуйте', comma=',', recipient='Александра', exclamation_point='!' ) print(message)
Параметры comma и exclamation_point всегда будут равны запятой и восклицательному знаку. Их надо делать частью шаблона:
message_template = ", !" message = message_template.format( greeting='Здравствуйте', recipient='Александра', ) print(message)
Если заранее известно, что и приветствовать мы всегда будем словом “Здравствуйте”, оно тоже станет частью шаблона:
message_template = "Здравствуйте, !" message = message_template.format(recipient='Александра') print(message)
Сложение
Как было упомянуто в статье про арифметические операции над строками, их лучше избегать:
person1 = 'Александра' person2 = 'Александр' message = """Здравствуйте, """ + person1 + """! На связи """ + person2 + """. . С уважением, """ + person2 print(message)
Такие строки трудно читать и изменять.
replace
person1 = 'Александра' person2 = 'Александр' message_template = """Здравствуйте, ! На связи . . С уважением, """ message = message_template.replace('', person1) message = message.replace('', person2) print(message)
В сущности аналогичен .format , но менять количество и название переменных уже труднее. А ещё .format умеет, например, выравнивать строки, а replace так не может.
Как ещё можно
В моменты, когда нужно форматирование строки в стиле printf (функции из популярного системного языка C), используют оператор %.
Начиная с версии 3.6 в Python появились f-строки — более удобная замена .format .
С особо редких случаях прибегают к Template Strings.
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
How to put a variable inside a string in Python?
In this article, we will learn to put variable’s value inside a string using Python Programming language. This can be very helpful where a statement is same but some value we get from an any other source like API changes daily. In that scenario we need to figure out a way to put the value of that variable in the statement. Let’s see some of these methods in Python.
Table Of Contents
Put a variable inside a string using f-string
The first method we will be using is the f-string method. Also known as the Literal String Interpolation. To create a f-string you need to add f as a prefix to string and curly braces in the place of variable. It can be used with multiple variables.
temp = 45 # f prefix denotes the f-string and variable temp # is enclosed with curly braces. statement = f"Today's maximum temperature is expected to be degrees Celsius" print(statement)
Frequently Asked:
Today's maximum temperature is expected to be 45 degrees Celsius
In the code and output above, you can see how easy and helpful is the f-string method, to put a variable’s value inside a string. Just add f as prefix before the double quotes and enclose variable in the curly braces.
Put a variable inside a string using format() method
Next method that we will be using is the format() method. It is the built-in string class method, which provides formatting options of the strings in Python. Just insert curly braces in the string and provide the variable in format() method as a parameter.
It recives only one parameter which is the str/value which needs to formatted. See an example below :
temp = 45 # provide curly braces where you need the variable's value. statement = "Today's maximum temperature is expected to be <> degrees Celsius" # provide variable as an argument in the format() method strValue = statement.format(temp) print(strValue)
Today's maximum temperature is expected to be 45 degrees Celsius
In the code and output above, you can see that by using format() method we have successfully inserted the value of variable temp in the statement. Just put a pair of curly braces at the place where you need to put the variable’s value. You can also add multiple variable inside a single string. Just pass all the variables as argument sequence wise, like the value needed in the first curly braces should be in first place as an argument.
Put a variable inside a string using String Concatenation
Next we will be using the string concatenation to put a variable’s value inside a string. String Concatenation is adding strings using + operator. Here we will be adding our variable inside the string using the + operator. This method has one drawback, it only concatenates strings not int or any other data type. If you need any int value as a variable’s value, first you need to convert it to string using the str() method otherwise it will throw a TypeError. Let’s see an Example :
temp = 45 # + operator is used at our desired place where we need to # put our variable's value also int has been converted to # str using str() function. statement = "Today's maximum temperature is expected to be " + str(temp) + " degrees Celsius" print(statement)
Today's maximum temperature is expected to be 45 degrees Celsius
So in the code and output above you can see the use of string concatenation and by using it we put variable temp’s value inside the string. We have also used str() method to convert int to str, since it accepts only string.
Put a variable inside a string using % Operator
Next we will be using the % Operator to put a variable’s value inside a string. This is very old method and used in other programming language like c. The %s is used for string and %d is used for integer. Let’s see an Example :
temp = 45 # Since we are using an integer so we will use %d # at the place where we need our variable's value. statement = "Today's maximum temperature is expected to be %d degrees Celsius" % temp print(statement)
Today's maximum temperature is expected to be 45 degrees Celsius
In the code and output above you can see we have successfully put the temp variable’s value inside the statement variable by using % operator. We have used %d for integer and also need to denote the variable at the end like here temp has been denoted with % operator.
Summary
In this article we learned to put a variable’s value inside a string using the Python programming language. We learned about four different methods.
Most useful method is format() method as it is easy to understand and you just need to pass value as an argument and denote curly braces at the place of variable. In other methods like method 3 and method 4 are smaller but a mistake can lead you to an error. Make sure to learn each and every method and always run these codes in your machines. We have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.
Related posts:
Python: Add Variable to String & Print Using 4 Methods
In this tutorial, we’re going to learn 4 methods to insert a variable into a string.
Method #1: using String concatenation
In the first method, we’ll concentrate a variable with a string by using + character.
If your variable type is an integer, you must convert it to a string before concatenation.
To convert, we’ll use the str() function.
Method #2: using the «%» operator
With the «%» operator, we can insert a variable into a string.
%s: for string.
%d: for integer.
Let’s see how to use the method?
inserting multi variables:
insert an integer variable into a string using %d:
Method #3: using the format() function
Another method to insert a variable into a string is using the format() function.
and <> I'm Pytutorial I'm <> years old".format(variable_1, variable_2, age) #print print(insert_var)
Method #4: using f-string
f-string is my favorite method to insert a variable into a string because it’s more readable.
Let’s see how to use it.
Note: this method works on Python >= 3.6.
and I'm Pytutorial I'm years old" #print print(insert_var)
Conclusion
In this tutorial, we’ve learned four methods to insert a variable into a string. All methods work perfectly.
Happy codding.
Related Tutorials:
How to place Variables in String in Python?
To place variables in string, we may use formatted string literals.
Place the character f before you start a string literal with single/double quotes as shown below.
Now, we can reference variables inside this string. All we need to do is enclose the variables with curly braces and place this variable inside the string value, wherever required. A quick example is given below.
Python Program
var1 = 'ABC' mystring = f'hello ' print(mystring)
In the above program, we have a variable named var1 and we inserted this variable in the string using formatted strings.
Examples
1. Write variables in strings
In this example, we will take integers in variables and try to insert these variables inside the string using formatted string.
Python Program
x = 25 y = 88 mystring = f'The point in XY plane is (,)' print(mystring)
The point in XY plane is (25,88)
2. Format string values in a given string
In this example, we will take string values in variables, name and place, and try to insert these variables inside the string using string formatting.
Python Program
name = 'ABC' place = 'Houston' mystring = f'My name is . I live in .' print(mystring)
My name is ABC. I live in Houston.
Summary
In this tutorial of Python Examples, we learned how to place variables in string literal, with the help of example programs.
Quiz on
Q1 . What is the output of the following program?
x = 12 print(f'The value of x is .')