Jake Strouse
Jake Strouse

Reputation: 58

Place a string within a string

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?

Upvotes: 3

Views: 159

Answers (5)

timgeb
timgeb

Reputation: 78690

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.

Upvotes: 3

atline
atline

Reputation: 31584

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

Upvotes: 0

Osman Mamun
Osman Mamun

Reputation: 2882

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))

Upvotes: 0

iDrwish
iDrwish

Reputation: 3103

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)'

Upvotes: 0

Kapocsi
Kapocsi

Reputation: 1032

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.

Upvotes: 1

Related Questions