Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

문장의 각 단어를 뒤집는 Python 프로그램?

<시간/>

여기서는 파이썬 내장 함수를 사용합니다. 먼저 문장을 단어 목록으로 나눕니다. 그런 다음 각 단어를 뒤집고 새 목록을 만듭니다. 여기에서는 파이썬 목록 이해 기술을 사용하고 마지막으로 새 단어 목록을 결합하고 새 문장을 만듭니다.

Input :: PYTHON PROGRAM
Output :: NOHTYP MARGORP

알고리즘

Step 1 : input a sentence. And store this in a variable s.
Step 2 : Then splitting the sentence into a list of words.
   w=s.split(“”)
Step 3 : Reversing each word and creating a new list of words nw.
Step 4 : Joining the new list of words and make a new sentence ns.

예시 코드

#  Reverse each word of a Sentence
 # Function to Reverse words
def reverseword(s): 
   
   w = s.split(" ")        # Splitting the Sentence into list of words.
                           # reversing each word and creating a new list of words
                           # apply List Comprehension Technique
   nw = [i[::-1] for i in w]
                           # Join the new list of words to for a new Sentence
   ns = " ".join(nw)
   return ns
# Driver's Code 
s = input("ENTER A SENTENCE PROPERLY ::")
print(reverseword(s))

출력

ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM
NOHTYP MARGORP