[英]How to replace a specific character in a string (python)
我正在嘗試在 Python 中生成凱撒密碼。我快完成了,但是在轉換像' '
這樣的字符的ord()
時遇到了問題
message = input('What is your message? ')
shift = input('What number do you want to shift the letters in your message by? ')
def Cipher(message,shift):
final_cipher = ''
for ch in message:
shift_convert = ord(ch) + int(shift)
print(shift_convert)
Cipher(message,shift)
當我使用消息"test run"
和2
的偏移運行此代碼時,我得到以下信息:
118
103
117
118
34
116
119
112
我將如何更改shift_convert
中的34
和僅34
? 我正在考慮減去移位值以將其變回' '
但我不知道如何實現。 你能給我一些提示嗎?
如果我理解你的問題是正確的,你不想改變 space/34,對吧? 您可以檢查ord(char)
是否為 32。
message = input('What is your message? ')
shift = input('What number do you want to shift the letters in your message by? ')
def Cipher(message,shift):
final_cipher = ''
for ch in message:
shift_convert = ord(ch) + int(shift) if ord(ch) != 32 else ord(ch)
print(shift_convert)
Cipher(message,shift)
您可以將if
else
語句添加到shift_convert
變量中:
shift_convert = ord(ch) + int(shift) if ch != ' ' else 32
試試這個,只需添加一個 if 語句來檢查它是否是一個空格
message = input('What is your message? ')
shift = input('What number do you want to shift the letters in your message by? ')
def Cipher(message,shift):
final_cipher = ''
for ch in message:
if(ord(ch) != 32):
shift_convert = ord(ch) + int(shift)
print(shift_convert)
else:
print(ord(ch))
Cipher(message,shift)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.