Re: [問題] 如何複製string

看板Python作者 (luckid)時間4年前 (2019/10/05 23:49), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《rongrong421 (R1VERK1D)》之銘言: : 我發現python的字串不能直接用賦值運算符號=複製 : 那請問要如何複製字串a的值到字串b呢? 小弟剛學python不久,想說用正則解決此問題,希望有所幫助, 寫得不對的地方請不吝指正,感謝: #引用正則module import re print('type a word for guessing:') #取得要猜的原始單字 ans=input() #判定使用者輸入的字串 # 規則:需為至少兩個字母長的小寫英文單字(此處未判斷該單字是否確實存在) regexAns=re.compile(r'^[a-z]{2,}$') chkAns=regexAns.search(ans) # 使用者輸入不合法字串則要求重新輸入 while chkAns is None: print('please TYPE A WORD(at least 2 characters long) for guessing,thank you.') print('type a word for guessing:') ans=input() chkAns=regexAns.search(ans) # 使用者輸入合法字串 # 開始猜單字 # 根據使用者輸入的字串產生"*"構成的字串存入final變數中 ex:若使用者輸入 "word",final變數會存入"****" print("Start guessing") final="*"*len(ans) print(final) # 要求使用者輸入字母 print('Please type alaphabet:') guess=input() # 判定使用者輸入是否合法 # 規則:需為單一字元的英文小寫字母 regexGuess=re.compile(r'^[a-z]{1}$') chkGuess=regexGuess.search(guess) regexFinal=re.compile(r'[\*]+') chkFinal=regexFinal.search(final) list_guess=[] while True: # 使用者輸入不合法 # 要求重新輸入 if chkGuess is None: print('please TYPE ONE LOWER-CASE ALPHABET ONLY,thank you.') guess=input() chkGuess=regexGuess.search(guess) # 使用者輸入合法字母 # 將該字母存入list_guess變數中 # 不去判斷字母有無重複,因為不影響之後的取代 list_guess.append(guess) # 此處的正則表達規則: # r[^字母1|字母2|...] # ans變數是存放正確的單字解答 # 所以可用取代的方式,將ans變數中不符合r[^字母1|字母2|...]規則的字母全部取代 為"*" # 例: # 假設ans為"word" # 使用者若輸入"a",則會將"不是a的字母"全部取代為"*",存入final中-->使用者會看 到的是"****" # 使用者若輸入"w",則會將"不是w的字母"全部取代為"*",存入final中-->使用者會看 到的是"w***" (w不會被取代) if len(list_guess)==1: myregex="[^"+list_guess[0]+"]" else: myregex="[^"+"|".join(list_guess)+"]" # 此處的正則表達式是用於判定final變數中還有沒有"*"字元的存在 # 若為None值,表示final變數已全為字母,使用者已得到正確答案,跳出迴圈 regexReplace=re.compile(rf'{myregex}') final=regexReplace.sub("*",ans) chkFinal=regexFinal.search(final) if chkFinal is None: break print(f'{final}') print('keep trying') guess=input() print(f'GJ! the word FOR guessing is : {ans}') -- https://www.youtube.com/watch?v=B_CMmbFexbM
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.236.11.54 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1570290571.A.67B.html
文章代碼(AID): #1TcBkBPx (Python)
討論串 (同標題文章)
文章代碼(AID): #1TcBkBPx (Python)