用 'X' 替换所有大写字符,用 'x' 替换所有小写字符,同时保持所有空格或符号相同

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

我正在尝试创建一个代码,将输入字符串替换为 'anonymous' 代码。我想用 'X' 替换所有大写字符,用 'x' 替换所有小写字符,同时保持任何空格或符号相同。

我理解<<变量>>.replace<<旧值,新值>>iffor 循环,但我无法执行它们来执行我想要的操作,请帮忙?

抱歉,如果我发布的代码不正确,我是新手

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 )

python 中的字符串是不可变的,因此您需要通过循环输入来构建一个新字符串。

在您的代码中,lower.replace(input, "x") 没有这样做 - 表示用 x 替换字母表的内容,其字符与您的输入匹配。换句话说,您想改为 input.replace ,但显然不会尝试插入整个字母表。


下面是一个在不输入字母表的情况下检查字符大小写的示例

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))

例如,另一种解决方案是使用 re.sub"[A-Z]", "X",但这取决于您了解它们的工作原理

有标准函数可以指示字符是 uppercase or lowercase。它们支持 Unicode(在 Python 3 和更新版本中),因此它们也可以处理重音字符。所以你可以使用

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

其中 text 是您的输入字符串。例如,

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)

与输入

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

结果

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