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
-
3Why do you have xxxxx?Padraic Cunningham– Padraic Cunningham2016年05月12日 01:04:03 +00:00Commented May 12, 2016 at 1:04
-
@PadraicCunningham, just an example of placeholder. :)Lin Ma– Lin Ma2016年05月12日 03:39:27 +00:00Commented May 12, 2016 at 3:39
6 Answers 6
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]']
1 Comment
[a.format(name) for name in names] instead of the mapuse 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
arr=["foo","goo","zoo"]
a="hello values: [xxxxx], have a good day"
for el in arr:
print(a.replace("xxxxx",el))
Comments
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
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
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