How To Add Randomly Generated Characters In Specific Locations In A String?
Solution 1:
This will work fine:
importstring, random
def encrypt():
data = "hello"
content = data[::-1]
encryption_str = 2
characters = string.ascii_uppercase +string.ascii_lowercase+string.digits
res = ""
res+=content[0]
for i in range(1,len(content)):
for j in range(encryption_str):
res+=random.choice(characters)
res+=content[i]
print(res)
encrypt()
Output
oLal5ilWremph
Solution 2:
Some issues:
With
random.choice(characters).join
you are generating one random character and use that as (repeated) separator. Instead you would need to repeatedly generate a new random characterWith
content[i:i + encryption_str]
you are slicing characters from the input string that are thus not separated.
Here is how you could do it with list comprehension:
res = content[0] + "".join(
ch + "".join(random.choice(characters) for _ inrange(strength))
for ch in content[1:]
)
Solution 3:
You're making this way too hard. All you need is a loop or comprehension that iterates through your content, inserting a pair of random characters. Since your purpose is obfuscation, rather than anything truly cryptic, I expect that you don't need replacement -- it's okay if you don't have a pair of identical characters inserted. This lets you take a slight shortcut with random.sample
.
content = "olleh"
result= [content[0]]
forcharin content[1:]:
result.extend(random.sample(characters, 2))
result.append(char)
print(''.join(result))
Output:
o8ulTklKBeBTh
I'll leave you to collapse it back to a one-liner.
Post a Comment for "How To Add Randomly Generated Characters In Specific Locations In A String?"