3

I want to do something along the lines of

print("hello, your name is [name]")

but I don't want to do it like

print("hello, your name is "+name) 

because I want to be able to place [name] anywhere in the string.

Is there some way to do this in python?

timgeb
  • 76,762
  • 20
  • 123
  • 145
Jake Strouse
  • 58
  • 1
  • 10

5 Answers5

3

Option 1, old style formatting.

>>> name = 'Jake'
>>> print('hello %s, have a great time!' % name)
hello Jake, have a great time!

Option 2, using str.format.

>>> print('hello {}, have a great time!'.format(name))
hello Jake, have a great time!

Option 3, string concatenation.

>>> print('hello ' + name + ', have a great time!')
hello Jake, have a great time!

Option 4, format strings (as of Python 3.6).

>>> print(f'hello {name}, have a great time!')
hello Jake, have a great time!

Option 2 and 4 are the preferred ones. For a good overview of Python string formatting, check out pyformat.info.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 2
    It's just missing [template strings](https://docs.python.org/3/library/string.html#template-strings). – shmee Oct 18 '18 at 05:51
1
print(f"hello, your name is {name}")

It is called an f-string: https://docs.python.org/3/reference/lexical_analysis.html#f-strings

There are other methods as well.

Kapocsi
  • 922
  • 6
  • 17
0

This is called string formatting: print('Hello, my name is {}'.format(name))

You can do something more complex as well:

print('Hello, my name is {0}, and here is my name again {0}'.format(name)'
iDrwish
  • 3,085
  • 1
  • 15
  • 24
0

From python3.6 you can use f string:

print(f'your name is {name}')

Or you can use format:

print('your name is {}'.format(name))
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
0

print("hello, your name is %s" % ('name')) also works for you.

You can extend it to more variables like:

>>> print("%s, your name is %s" % ('hello', 'name'))
hello, your name is name
atline
  • 28,355
  • 16
  • 77
  • 113