简体   繁体   中英

replacing multiple characters in string with random digits/uppercase/lowercse Python

i have a string,

str = 'B?l35?uAA8-A47E-4?d?d5-?d?dDC-C?dC?d?d?d?dF?lF?dE'

i want to replace all ?d with random digits, all ?l with random lowercase, all ?u with random uppercase.

You can use random.randint() and random.choice() to get random values for digits and alphabets. The variable inside choice has to be a list of all the alphabets.

You search through the full string one char at a time, then for each ?l or ?u or ?d , you can replace the string with the desired result.

Here's a sample code I wrote to do this. Obviously, it can be improved but I wanted to give you a basic code to work with.

import random
s = 'B?l35?uAA8-A47E-4?d?d5-?d?dDC-C?dC?d?d?d?dF?lF?dE'
r = list(s)
a = list('abcdefghijklmnopqrstuvwxyz')
print (s)
for i,x in enumerate(s):
    if x == '?':
        if s[i+1] == 'l':
            r[i+1] = random.choice(a)
        elif s[i+1] == 'u':
            r[i+1] = random.choice(a).upper()
        elif s[i+1] == 'd':
            r[i+1] = str(random.randint(0,9))
r = ''.join(x for x in r if x != '?')
print (r)

Output of the above code for multiple runs are:

B?l35?uAA8-A47E-4?d?d5-?d?dDC-C?dC?d?d?d?dF?lF?dE
Be35ZAA8-A47E-4415-10DC-C9C0915FjF7E

B?l35?uAA8-A47E-4?d?d5-?d?dDC-C?dC?d?d?d?dF?lF?dE
Bl35DAA8-A47E-4985-26DC-C9C0455FxF6E

B?l35?uAA8-A47E-4?d?d5-?d?dDC-C?dC?d?d?d?dF?lF?dE
Bn35KAA8-A47E-4235-70DC-C1C5504FuF0E

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM