pythonanonymize

Replace all upper case characters with 'X' and all lower case characters with 'x' whilst keeping any spaces or symbols the same


I am trying to create a code where I substitute an input string into an 'anonymous' code. I would like to replace all upper case characters with 'X' and all lower case characters with 'x' whilst keeping any spaces or symbols the same.

I understand << variable >>.replace<< old value, new value >> and if and for loops, but am having trouble implementing them to do what I want, please help?

Sorry if the code I posted isn't proper, I'm new to this

input_string   =  input( "Enter a string (e.g. your name): " ) 
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

for input in input_string:
    if input in input_string:
        input_string = lower.replace(input, "x")

    if input in upper:
        input_string = upper.replace(input, "X")`

print( "The anonymous version of the string is:", input_string )

Solution

  • There are standard functions to indicate a character is uppercase or lowercase. These are Unicode aware (in Python 3 and newer) so they also work with accented characters. So you can use

    ''.join('x' if x.islower() else 'X' if x.isupper() else x for x in text)
    

    where text is your input string. For example,

    input_string   =  input( "Enter a string (e.g. your name): " ) 
    result = ''.join('x' if x.islower() else 'X' if x.isupper() else x for x in input_string)
    

    with the input

    I am trying to create a code where I substitute an input string into an 'anonymous' code.
    

    results in

    "X xx xxxxxx xx xxxxxx x xxxx xxxxx X xxxxxxxxxx xx xxxxx xxxxxx xxxx xx 'xxxxxxxxx' xxxx."