挑战:编写一个以字符串作为参数的函数,并创建一个新的字符串作为参数的副本,但每个非字母都替换为空格 (例如,“pl @ dz& y”变为“pl dz y”)。 要编写这样的函数,您将以空字符串开头,并逐个遍历参数的字符。遇到可接受的字符时,将其添加到新字符串中。如果不可接受,则为新字符串添加空格。请注意,您可以通过简单比较检查字符是否可接受。例如,可以使用测试找到任何小写字母。
到目前为止我的尝试:
def character_replacement( string ):
string_new = ""
for char in string:
if char >= 'a' and char <= 'z' == True:
string_new += char
if char >= 'A' and char <= 'Z' == True:
string_new += char
if char >= 'a' and char <= 'z' == False:
string_new += " "
if char >= 'A' and char <= 'Z' == False:
string_new += " "
return string_new
string = input( "Input string, with or without special characters: " )
character_replacement(string)
仍在努力编写一个有效的功能以及如何“打印”或“返回”某些内容。
答案 0 :(得分:0)
==
在and
之前进行评估。您可以用括号括起条件以获得正确的结果:
if (char >= 'a' and char <= 'z') == True:
string_new += char
if (char >= 'A' and char <= 'Z') == True:
string_new += char
if (char >= 'a' and char <= 'z') == False:
string_new += " "
if (char >= 'A' and char <= 'Z') == False:
string_new += " "
或者只是省略==
部分,并评估你的布尔表达式:
if char >= 'a' and char <= 'z':
string_new += char
if char >= 'A' and char <= 'Z':
string_new += char
if not (char >= 'a' and char <= 'z'):
string_new += " "
if not (char >= 'A' and char <= 'Z'):
string_new += " "
编辑:
请注意,使用内置isalpha()
方法可以使这更加优雅:
if char.isalpha():
string_new += char
else:
string_new += " "
当你在它的时候,你可以重写整个方法作为对字符串字符的理解:
def character_replacement(s):
return "".join(c if c.isalpha() else " " for c in s)