string - Getting data for replacement (python 3.3) -


for example, have string or list of such strings:

text = '000 #-tags-2-7-# 001 002 003 004 05 06 07 08 sdfgsdfg #-tags-3-9-#' keys = ['key-1', 'key-2', 'key-3', 'key-4', 'key-5', 'key-6', 'key-7', 'key-8', 'key-9', 'key-10'] 

and need replace #-tags-2-7-# on result keys[randint(2, 7)] , #-tags-3-9-# on keys[randint(2, 7)] etc. need every time 2 integers #-tags---# , send keys[randint(*, *)] , send result instead #-tags---#

you use re.sub replace pattern r'#-tags-(\d)-(\d)-#' desired string:

import re import random text = '000 #-tags-2-7-# 001 002 003 004 05 06 07 08 sdfgsdfg #-tags-3-9-#' keys = ['key-1', 'key-2', 'key-3', 'key-4', 'key-5', 'key-6', 'key-7', 'key-8', 'key-9', 'key-10']  def tag_replace(match):     start, end = map(int, match.groups())     return ', '.join(random.sample(keys, random.randint(start, end)))  print(re.sub(r'#-tags-(\d)-(\d)-#', tag_replace, text)) 

prints (a random result such as)

000 key-8, key-7, key-3 001 002 003 004 05 06 07 08 sdfgsdfg key-9, key-1, key-7, key-3, key-4, key-10, key-6 

note: take want #-tags-3-9-# replaced comma-separated list of n items keys, n = random.randint(3, 9).


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -