jeudi 10 novembre 2022

Randomly replacing letters, numbers, and punctuation in a string: can this code be condensed?

Writing a function to check an input string for numbers, and if there are any, to randomize every digit, letter, and punctuation mark in the string. (i.e. "hello3.14" might become "jdbme6?21")

This code works (and the goal makes sense in context, I promise) but it sure seems redundant. Not sure how to tighten it up. The ELSE is just there to make me feel better about loose ends, but it's probably disposable.

My primary question is, Can this method be condensed? Secondary question, Is there a completely different, better way I should do this? Thanks for any guidance.

import random
import string


def new_thing(old_thing):
    output_str = ''
    if any(char.isdigit() for char in old_thing):
        for char in old_thing:
            get_new = char
            if char in string.digits:
                while get_new == char:
                    get_new = random.choice(string.digits)
                output_str += get_new
            elif char in string.ascii_lowercase:
                while get_new == char:
                    get_new = random.choice(string.ascii_lowercase)
                output_str += get_new
            elif char in string.punctuation:
                while get_new == char:
                    get_new = random.choice(string.punctuation)
                output_str += get_new
            else:
                output_str += char
        print(output_str)
    else:
        print("lol no numbers gg")


new_thing(input("Type a thing: ").lower())



Aucun commentaire:

Enregistrer un commentaire