-4

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 ?

Makaveli
  • 9
  • 5
  • 1
    Please put more effort into your work before asking a question. https://docs.python.org/3/library/stdtypes.html#str.format – Gabriel Apr 13 '18 at 21:01

3 Answers3

1

You can use format for the same

"hello {0}".format("Hello") 
py-D
  • 661
  • 5
  • 8
0

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.

Azsgy
  • 3,139
  • 2
  • 29
  • 40
  • care to explain the downvote? On both of these answers? – Azsgy Apr 13 '18 at 21:01
  • and what if i want to use more variables like {0} {1} {2} {3}. – Makaveli Apr 13 '18 at 21:04
  • I've shown you this in the second snippet, simply add more arguments to format – Azsgy Apr 13 '18 at 21:05
  • @Makaveli You can. When each argument to format is used only once, and in left-to-write order, you can omit numbers from the placeholders. (That is, `format` has an algorithm for inferring the next number to use with `{}`.) – chepner Apr 13 '18 at 21:05
0

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.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27