HomeComputer SciencePracticalClass 12Longest Word Shifting

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

Longest Word Shifting Left

AIM

To write a Python program to shift the longest word in a sentence to the left.

ALGORITHM

  1. Start
  2. Input a sentence
  3. Split the sentence into words
  4. Find the longest word
  5. Shift the longest word to the left
  6. Output the modified sentence
  7. Stop

PROGRAM

# Python program to shift the longest word in a sentence to the left

def shift_longest_word_left(sentence):
    words = sentence.split()
    longest_word = max(words, key=len)
    longest_word_index = words.index(longest_word)
    words[longest_word_index] = longest_word[1:] + longest_word[0]
    return ' '.join(words)

sentence = input("Enter a sentence: ")
modified_sentence = shift_longest_word_left(sentence)
print("Modified sentence:", modified_sentence)

OUTPUT

Enter a sentence: Hello world from Python

Modified sentence: Hello wolrd from Python

CONCLUSION

Thus, the given program was successfully executed and the output was verified as per the expected result.

VIVA QUESTIONS

  1. What is string manipulation in Python?

    String manipulation in Python refers to the process of modifying strings, such as changing their case, splitting them, joining them, or extracting substrings.

  2. How do you find the longest word in a sentence using Python?

    You can find the longest word in a sentence by splitting the sentence into words and using the max function with the key parameter set to len.

  3. What does the slicing operation word[1:] + word[0] do in Python?

    The slicing operation word[1:] + word[0] takes a word and shifts its first character to the end, effectively rotating the word to the left by one position.