in C# it was Possible to Use a Code Like This:
Console.WriteLine ("hello{0}" ,Hello);
i Want to do Same Thing in Python,i Want to Call Variable With {0} and {1} Way. How Can I Do This ?
in C# it was Possible to Use a Code Like This:
Console.WriteLine ("hello{0}" ,Hello);
i Want to do Same Thing in Python,i Want to Call Variable With {0} and {1} Way. How Can I Do This ?
You can use the str.format
function:
"Hello {0} {1}".format(firstname, lastname)
You can also leave the space in between the {}
blank to automatically pick the next argument:
>>> "{}, {}".format("one", "two")
one, two
You can also use a prettier "f string" syntax since python 3.6:
f"Hello{Hello}"
The variable inside the {}
will be looked up and placed inside the code.
You can use place holders to format strings in Python. So in this example, if you want to use a place holder such as {0}, you have to use a method called .format in Python. Below is a mini example.
name = input('Please enter your name: ')
with open('random_sample.txt', 'w') as sample:
sample.write('Hello {0}'.format(name))
As you can see, I ask the user for a name and then store that name in a variable. In my string that I write to a txt file, I use the place holder, and outside of the string I use the .format method. The argument that you enter will be the variable that you want to use.
if you want to add another variable {1} you would do this:
sample.write('Hello {0}. You want a {1}').format(name, other_variable))
so whenever you use a placeholder like this in Python, use the .format() method. You will have to do additional research on it because this is just a mini example.