0

Want to find an elegant way to replace xxxxx part dynamically with an array of values (xxxxx is more like a template placeholder for real string values). For example, if the array is ["foo","goo","zoo"], I want to generate 3 dynamic strings

a="hello values: [xxxxx], have a good day"

Dynamic string expected,

"hello values: [foo], have a good day"
"hello values: [goo], have a good day"
"hello values: [zoo], have a good day"

thanks in advance, Lin

2
  • 3
    Why do you have xxxxx? Commented May 12, 2016 at 1:04
  • @PadraicCunningham, just an example of placeholder. :) Commented May 12, 2016 at 3:39

6 Answers 6

2

The perfect use for map() even though list comprehensions are the newer, more idiomatic way to do it.

>>> a = "hello values: [{}]"
>>> names = ["foo", "goo", "zoo"]

>>> map(a.format, names)

['hello values: [foo]', 
 'hello values: [goo]', 
 'hello values: [zoo]']
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best Pythonic answer. You could also do [a.format(name) for name in names] instead of the map
1

use string replace function.

a.replace("xxxxxx", "foo")

for a list:

src_name = ["foo", "goo", "zoo"]
a = "hello values: [xxxxx], have a good day"
result = (a.replace("xxxxx", d) for d in src_name)
for i in result:
    print (i)

output:

hello values: [foo], have a good day
hello values: [goo], have a good day
hello values: [zoo], have a good day

1 Comment

Thanks for the help Mrunmoy, vote up and mark your reply as answer.
1
arr=["foo","goo","zoo"]
a="hello values: [xxxxx], have a good day"
for el in arr:
  print(a.replace("xxxxx",el))

Comments

1

The replace function is what you're looking for :

a.replace('xxxxx','stringtoreplace')

if you want to go through the array then :

for str in stringarray:
     print(a.replace('xxxxx',str))

Comments

1

My first intension is:

sentence = "hello values: [xxxxx], have a good day"
names = ["foo", "goo", "zoo"]

sentences = [sentence.replace("xxxxx", name) for name in names]

But I have a bad smell about your application ... it's a uncommon question.

Comments

0

I will loop through the array and perform regular expression on it.

Looking for a pattern occurence of "[xxxxx]" and replacing that with whatever the array value is.

You can also just simply replace xxx with the array value but that can be unreliable anchoring to [xxx] is much safer as that is stricter.

Python's regular expression API. https://docs.python.org/2/library/re.html

1 Comment

Thanks. Vote up on the question too because I don't see how this is a troll question, which have already received -2 response. Everyone start somewhere, especially topic on string manipulation.

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.