我正在嘗試制作一個代碼來查找特殊字符并將它們替換為*.
例如:
L!ve l@ugh l%ve
這應該更改為
L*ve l*ugh l*ve
這是我迄今為止嘗試過的
a = input()
spe = " =/_(*&^%$#@!-.?)"
for i in a:
if i in spe:
b = a.replace(i,"*")
else:
b = i
print(b,end="")
這會回傳類似這樣的內容
Lve lugh lve
為什么我會變成這樣?
以及如何解決這個問題?
uj5u.com熱心網友回復:
一個簡單的方法:
import string
all_chars = string.ascii_letters
a = 'L!ve l@ugh l%ve'
for item in a:
if item ==' ':
pass
elif item not in all_chars:
item='*'
print(item, end="")
uj5u.com熱心網友回復:
您正在嘗試修改整個字串,而您應該只處理該字符。
修改您的代碼,這將是:
a = '(L!ve l@ugh l%ve)'
spe = set(" =/_(*&^%$#@!-.?)") # using a set for efficiency
for char in a:
if char in spe:
print('*', end='')
else:
print(char, end='')
輸出:*L*ve l*ugh l*ve*
一種更 Pythonic 的方式是:
spe = set(" =/_(*&^%$#@!-.?)")
print(''.join(['*' if c in spe else c for c in a]))
uj5u.com熱心網友回復:
當您到達 if 陳述句并且如果滿足條件時,它將進入分支并執行。如果您只想列印可以運行的陳述句:
a = input()
spe = " =/_(*&^%$#@!-.?)"
for i in a:
if i in spe:
b = "*"
print(b)
else:
b = i
print(b,end="")
但您也可以將其保存為字串
a = input()
new_string = ""
spe = " =/_(*&^%$#@!-.?)"
for i in a:
if i in spe:
new_string = "*"
else:
new_string = i
print(new_string)
uj5u.com熱心網友回復:
作為另一種選擇,您可以嘗試使用正則運算式。以下是兩種可能的方法,具體取決于您要如何定義字符集:
import re
print(re.sub('[^a-zA-Z\d\s]', '*', "L!ve l@ugh l%ve"))
print(re.sub("[$& ,:;=?@#|'<>.^*()%!-]", '*', "L!ve l@ugh l%ve"))
# L*ve l*ugh l*ve
uj5u.com熱心網友回復:
你的腳本有兩個問題:
- 如果找到特殊字符,則將它們替換為 b 而不是 I
- 只有在未找到特殊字符時才列印。
嘗試:
a = "L!ve l@ugh l%ve"
spe = " =/_(*&^%$#@!-.?)"
for i in a:
if i in spe:
b = i.replace(i,"*")
else:
b = i
print(b,end="")
或者,當我們替換原始字串中的字符時,我們可以在最后列印它:
a = "L!ve l@ugh l%ve"
spe = " =/_(*&^%$#@!-.?)"
for i in a:
if i in spe:
b = a.replace(i,"*")
else:
b = a
print(b)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438415.html
