编写Python程序以从用户读取句子,并在进行以下更改后再次打印该句子:
a
和A
转换为@
s
和S
转换为$
o
和O
转换为0
g
和G
转换为8
i
和I
转换为!
这是我的代码:
#user inputs a sentence
iSent=(input("Enter a sentence that you want to convert the letters of:"))
#Process of converting the letters
print(iSent.replace("s","$"))
print(iSent.replace("S","$"))
print(iSent.replace("o","0"))
print(iSent.replace("O","0"))
print(iSent.replace("g","8"))
print(iSent.replace("G","8"))
print(iSent.replace("i","!"))
print(iSent.replace("I","!"))
这是我的结果:
Enter a sentence that you want to convert the letters of:
Summer season is a great season
Summer $ea$on i$ a great $ea$on
$ummer season is a great season
Summer seas0n is a great seas0n
Summer season is a great season
Summer season is a 8reat season
Summer season is a great season
Summer season !s a great season
Summer season is a great season
如何编写此代码以一种方式将字母转换为1行而不是多行?
答案 0 :(得分:1)
您可以使用词典来存储要用其替换字母的符号(由于用相同的符号替换了大写和小写字母,因此只需要存储大写或小写的值):>
letters_to_symbols = {
'S': '$',
'O': '0',
'G': '8',
'I': '!'
}
然后循环浏览字典:
isEnt = input('enter your sentence here:\n')
for letter, symbol in letters_to_symbols.items():
isEnt = isEnt.replace(letter, symbol)
isEnt = isEnt.replace(letter.lower(), symbol)
print(isEnt)
结果是:
enter your sentence here:
>>> Summer season is a great season
$ummer $ea$0n !$ a 8reat $ea$0n
答案 1 :(得分:0)
您可以使用str.translate
:
>>> src = "asogi"
>>> tgt = "@$08!"
>>> text = "Summer season is a great season"
>>> text.translate(str.maketrans(src + src.upper(), tgt*2))
'$ummer $e@$0n !$ @ 8re@t $e@$0n'
这将用相应的字符替换'asogiASOGI'
中的字符。 '@$08!@$08!'
中的字符。
相反,如果您想一次只替换一个字符,但要减少行数,请使用zip
和一个循环(与问题中的输出相同):
for s, t in zip(src+src.upper(), tgt*2):
print(text.replace(s, t))