2016-10-29 4 views
0
1)Prompt the user for a string that contains two strings separated by a comma. 
2)Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. 
3)Using string splitting, extract the two words from the input string and then remove any spaces. Output the two words. 
4)Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. 

출력 된 단어에 첨부 할 수있는 여분의 공백을 제거하는 방법을 배울 수는 없지만이 지침이있는 프로그램을 작성했습니다. 예를 들어 "Billy, Bob"을 입력하면 잘 작동하지만 "Billy, Bob"을 입력하면 IndexError : list 인덱스가 범위를 벗어나거나 "Billy, Bob"을 입력하면 Billy가 문자열에 추가 공간이 있습니다. 여기 내 코드가있다.파이썬에서 문자열을 분할 한 후 공백을 제거합니다.

usrIn=0 
while usrIn!='q': 
    usrIn = input("Enter input string: \n") 
    if "," in usrIn: 
     tokens = usrIn.split(", ") 
     print("First word:",tokens[0]) 
     print("Second word:",tokens[1]) 
     print('') 
     print('') 
    else: 
     print("Error: No comma in string.") 

어떻게하면 출력에서 ​​공백을 제거하여 usrIn.split (",")을 사용할 수 있습니까?

답변

0

앞뒤 공백을 제거하는 .trim() 메서드를 사용할 수 있습니다. usrIn.trim().split(","). 이 작업이 완료되면 공백 문자 정규식을 사용하여 다시 나눌 수 있습니다 (예 : usrIn.split("\\s+") ). \s은 공백을 찾고 + 연산자는 반복되는 공백을 찾습니다.

희망이 도움이됩니다.

관련 문제