1

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

1
  • All values you want to replace val1, val2 and val3 with have to have a string representation if you want them to be in string1 Commented Jul 13, 2011 at 15:41

4 Answers 4

5

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Aaron Digulla's answer shows how to use format with a dictionary to produce very readable code.
4

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

Comments

3

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'

Comments

0

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'

1 Comment

thank you all for your answers. many of the suggested ways worked, but I have voted for the one that suited my code requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.