0

I am trying to create a python script that has 10-20 lines of fixed data in a string with 2 special character's that need to be replaced with a different, random string using randomword()

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))


junk = """
random_string1 = {};
random_string2 = {};
random_string3 = {};
random_string4 = {};
random_string5 = {};
"""

stra = string.replace(junk, '{}', randomword(40))
print (stra)

The two special characters in the string are {}, I would like to iterate through the string to find those characters and replace them with a different random string generated by randomword()

Above is as far as I got, this piece of code replaces all of the occurrences of {} with a random string, but they have the same values, I would like to have differing values for each {}.

I don't know how to put this into a loop. Any help is appreciated.

3 Answers3

1

Since you are already using the default placeholder for string formatting '{}', you can do:

>>> print(junk.format(*(randomword(40) for _ in range(junk.count('{}')))))

random_string1 = lazbdzezssemtsfknajawriafozpjwizigykvmac;
random_string2 = pxhkyrnjiqsvcivcppqqpbwuocsvbfauygdrwpuj;
random_string3 = ewhrsryjtfwtmulmqfqxzrzvyspiefrddpzrxkvq;
random_string4 = sqiulddoevddtieymjiexnmzezrdayvwigmsmgld;
random_string5 = evscqvrccknkulpkqchodcjlognsnrcxqcsexnrv;
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Works almost perfect, thanks! Just one thing, can it be so that the replacement only happens if the characters `{` and `}` are together, like this : `{}`, because if the text contains other `{` with new lines after the character it seem's to throw out errors. – Hunter.S.Thompson Dec 28 '17 at 21:55
  • That depends on what comes between the two. E.g. `{2}` will be replaced by the third (index 2) positional argument passed to `.format()`. For other details you can look at the linked docs. I was assuming you had exact `{}` in your string. – user2390182 Dec 28 '17 at 21:57
1

use randint(97, 122)

import random 


def randomword(length):
   s = ""
   for _ in range(length):
       a = random.randint(97, 122)
       s += chr(a)
   return s

def replace(original_string, string_to_replace):
    result_string = ""
    while original_string.find(string_to_replace) >= 0:
      pos = original_string.find(string_to_replace)
      result_string += original_string[0: pos]
      result_string += randomword(40)
      next_pos = pos+2
      original_string = original_string[next_pos:]
    result_string += original_string[:]
    return result_string

junk = """
random_string1 = {};
random_string2 = {};
random_string3 = {};
random_string4 = {};
random_string5 = {};
"""

stra = replace(junk, "{}")
print (stra)
Jai
  • 3,211
  • 2
  • 17
  • 26
1

Could use regex:

>>> print(re.sub('{}', lambda _: randomword(40), junk))

random_string1 = emgdidmmghkunqkwdfcnvsffdnfhvqrybhqdfklh;
random_string2 = mgggwchtzpuhntnfxzpsmkarkwnlghcwicnvxmpt;
random_string3 = liemdzegmzfpuozktclxnmfmavjkaxqhrfaldqkn;
random_string4 = ugchyijmsvzmeaiyzyaiudrnnfskzdboukvdwiye;
random_string5 = rfazvtvhygfixielqzbuhlnzvjjtrkhsdetomjri;
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • Is there anyway I can make sure that the random text created for each random_string is different from the ones created for earlier random_strings? – Hunter.S.Thompson Jan 02 '18 at 22:12
  • Sure, there are ways for that. But do you intend to use shorter strings now or not use the whole alphabet? And how many strings do you want to produce? – Stefan Pochmann Jan 02 '18 at 22:21
  • Currently I am using this answer to create random hexadecimal int, that are 2 characters long and replacing the `{}` with the value generated, there is a high chance that there is a pair that is the same. I would be creating more then 20-30 strings with the 2 characters as replacement instead of random string. Using this function: `binascii.b2a_hex(os.urandom(1))`, I could use the same answer for the random string and hexadecimal int, so that they do not ever repeat themselves – Hunter.S.Thompson Jan 02 '18 at 22:26
  • Ok, yeah, with such small numbers it's completely different. With your original numbers you couldn't produce duplicates if you tried :-). I'd maybe use `random.sample(range(256), n)` to pick n unique numbers (where n is how many you need). Or keep a set of the still-available or the already-used numbers and pick and update accordingly. – Stefan Pochmann Jan 02 '18 at 22:51