1

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 )
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

1

Strings in python are immutable, so you'll need to build a new one by looping over the input.

In your code, lower.replace(input, "x") isn't doing that - that says to replace the contents of the alphabet, whose characters match your input, with an x. In other words, you wanted to do input.replace instead, but obviously not try to insert the entire alphabet.


Here's an example that checks the case of the characters without typing out the alphabet

input_string = input( "Enter a string (e.g. your name): " ) 
output_string = []

for c in input_string: 
    if c.isupper(): 
        output_string.append('X')
    elif c.islower(): 
        output_string.append('x')
    else:
        output_string.append(c) 
print( "The anonymous version of the string is:", ''.join(output_string))

Another solution would be to use re.sub and "[A-Z]", "X", for example, but that's up to you to learn how those work

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
1

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."
Jongware
  • 22,200
  • 8
  • 54
  • 100