2016-09-19 3 views
0

파이썬 3.5 여기문자열 색인

내 코드입니다 : 그대로

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    print("That word was found!") 
else: 
    print("Sorry, that word was not found") 

, 그것은 입력 된 단어 (STR2)를 검색합니다 그것은 (입력 (str1이있는 문장을 발견하는 경우)) "단어가 발견되었습니다"라고 말할 것입니다. 그 단어가 문장에 없다면 "그 단어는 발견되지 않았다"고 말할 것입니다.

단어를 검색하여 찾았을 때 문장 (str1)의 단어 (str2)의 색인 위치를 사용자에게 알려주고 싶습니다. 그래서 예를 들면 : 문장 ("나는 Python으로 코딩하고 싶다")가 있고 단어 ("코드")를 검색하면 프로그램은 "그 단어가 색인 위치에서 발견되었습니다 : 4"라고 말해야합니다.

Btw 방법으로 코드는 대소 문자를 구분하지 않으므로 모든 단어를 .lower로 소문자로 변환합니다.

누구든지 내게이 조언을 줄 수 있다면 대단히 감사하겠습니다.

+0

Python 2.7 또는 Python 3을 사용하고 있습니까? – PrestonM

답변

1

당신은 대체 할 수있는 당신이에 의해 if ... else :

try: 
    print("That word was found at index %i!"% (str1.split().index(str2) + 1)) 
except ValueError: 
    print("Sorry, that word was not found") 
+0

고마워요, 저에게 도움이되었습니다. 원본 코드에 약간의 변화를 주어 멋지고 단순합니다. 내가 원했던 것입니다. 건배! :) –

+0

당신을 환영합니다. ;-) – trincot

0
print("That word was found at index %i!"% (str1.split().index(str2))) 

이렇게하면 str1에서 str2가 처음 나타나는 색인이 인쇄됩니다.
전체 코드는 다음과 같습니다

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    print("That word was found!") 
    print("that word was found in index position: %i!"% (str1.split().index(str2))) 

, str1.index (STR2)) 다른
: 인쇄 ("죄송합니다, 그 단어를 찾을 수 없습니다")

+1

정확하지 않습니다. 'str1.split() .index (str2)' –

+0

구문이 잘못되었습니다. –

+0

음 ... 구문 오류가 없습니다. 인용 부호로 둘러싸인 입력 내용을 입력 했습니까? – PrestonM

0
str2 = 'abcdefghijklmnopqrstuvwxyz' 
str1 = 'z' 
index = str2.find(str1) 
if index != -1: 
    print 'That word was found in index position:',index 
else: 
    print 'That word was not found' 

이것은 인쇄합니다 STR2에서 str1과의 지수는

+0

변수'str'의 이름을 지정하지 않고'ascii_lowercase'에서 문자열 가져 오기 –

+0

문자열을 가져올 수 있습니다. 그렇지만 Python을 처음 접했을 때 그 코드를 가져 오기와 혼동하고 싶지는 않습니다. . –

+0

고마워요, 저에게 도움이되었습니다. 그러나 어떤 이유로 든 올바른 색인 번호를주지 못합니다. 예를 들어, str1에 대해 "Python으로 코드를 작성하겠습니다"라고 말한 다음 "코드"를 검색하면 색인 위치 10에 있다고 알려줍니다. 이 문제를 해결할 수있는 방법이 있습니까? –

0

split() 메서드를 사용할 수 있습니다. 즉, 문자열 값에서 호출되고 문자열 목록을 반환합니다. 그런 다음 index() 메서드를 사용하여 문자열의 인덱스를 찾습니다.

str1 = input("Please enter a full sentence: ").lower() 
print("Thank you, You entered:" , str1) 
str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower() 

if str2 in str1: 
    a = str1.split() # you create a list 
    # printing the word and index a.index(str2) 
    print('The ', str2,' was find a the index ', a.index(str2)) 
    print("That word was found!") 
else: 
    print("Sorry, that word was not found") 
관련 문제