2014-03-30 2 views
0
inp = input("Enter word") 
inplen = len(inp) 

text = "sandwich" 
textlen = len(text) 

if inplen >= textlen: 
    if inp[0] == text[0]: 
     print("s") 
if inplen >= textlen: 
    if inp[1] == text[1]: 
     print("a") 
if inplen >= textlen: 
    if inp[2] == text[2]: 
     print("n") 
if inplen >= textlen: 
    if inp[3] == text[3]: 
     print("d") 
if inplen >= textlen:   
    if inp[4] == text[4]: 
     print("w") 
if inplen >= textlen:   
    if inp[5] == text[5]: 
     print("i") 
if inplen >= textlen:   
    if inp[6] == text[6]: 
     print("c") 
if inplen >= textlen: 
    if inp[7] == text[7]: 
     print("h") 

전체 "샌드위치"를 입력하지 않으면 출력이 표시되지 않습니다. 내가하려는 것은 프로그램이 "sandwhich"와 일치하는 모든 정확한 문자를 인쇄해야한다는 것입니다. 따라서 "샌드위치"를 입력하면 "s" "a" "n" "d" "w" "h"를 반환하고 "sand"를 입력하면 "s" "a" "n" "d"를 반환해야합니다. 감사왜이 문자열 처리가 작동하지 않습니까?

답변

2

: 단어는`potato` 같은 중복 문자가있는 경우

text = "sandwich" 
inp = input("Enter word") 

# a range from zero to the length of the shortest string 
# (if one string is longer than the other, we want the length of the shortest 
# one so that it doesn't try to check characters that don't exist) 
for i in range(min(len(text), len(inp))): 
    # print if corresponding characters match 
    if inp[i] == text[i]: 
     print(text[i]) 
0

당신은 간단하게 다음과 그렇게 할 수 있습니다

in_text = str(input("Enter word: ")) 
print(list(set(input) & set('sandwich'))) 

set(a) & set(b)ab 모두에 공통적 인 요소를 포함하는 집합을 반환합니다. 그런 다음 list()을 목록으로 변환 한 다음 인쇄합니다. 루프는 여기에 훨씬 쉬울 것

>>> print(list(set('sandstorm') & set('sandwich'))) 
['s', 'a', 'n', 'd'] 
+1

이 실패합니다 다음은 그 예이다. – Doorknob

+0

@Doorknob하지만 OP가 입력 한 글자 만 원하니? 교수형 집행 인처럼 캐릭터가 실제로 몇 번이나 등장 하느냐는 중요하지 않습니다. – sshashank124

+0

@Dorkorkob, 어쩌면 나는 너를 제대로 이해하지 못했을 것이다. 무슨 뜻인지 예를 들려 주시겠습니까? 감사 – sshashank124

관련 문제