Rinks
Rinks

Reputation: 1067

replace a substring with a non-string value in python

I know we have a replace method to replace a substring within a string with another string. But what I want is to replace some substring within a given string with some non-string (could be any data type) values.

example -

string1='My name is val1. My age is val2 years. I was born on val3'
val1='abc'
val2=40
val3= datetime.date(1980, 1, 1)

Any ideas??

Thanks!!

Upvotes: 1

Views: 441

Answers (4)

Aaron Digulla
Aaron Digulla

Reputation: 328614

I prefer to use a dict for that because it makes it much more simple to see which argument goes where:

'My name is {val1}. My age is {val2} years. I was born on {val3}'.format(
    val1 = 'abc',
    val2 = 40,
    val3 = datetime.date(1980, 1, 1)
)

Upvotes: 4

Michael J. Barber
Michael J. Barber

Reputation: 25042

Convert the value to string first:

>>> string1.replace("val2", str(val2))
'My name is val1. My age is 40 years. I was born on val3'

Upvotes: 0

Marcin
Marcin

Reputation: 238229

What about this:

string1='My name is %s. My age is %s years. I was born on %s'
print(string1 % ('abc', 40, datetime.date(1980, 1, 1)))

results in:

'My name is abc. My age is 40 years. I was born on 1980-01-01'

Upvotes: 3

senderle
senderle

Reputation: 150987

Use str.format:

>>> string1 = 'My name is {0}. My age is {1} years. I was born on {2}'
>>> string1.format('abc', 40, datetime.date(1980, 1, 1))
'My name is abc. My age is 40 years. I was born on 1980-01-01'

Upvotes: 5

Related Questions