Функция longest word python

Python Program to Find Longest Word From Sentence or Text

In this program, first we read sentence from user then we use string split() function to convert it to list. After splitting it is passed to max() function with keyword argument key=len which returns longest word from sentence.

This Python program finds longest word from a given text or sentence.

Python Source Code: Longest Word

 # Longest word # Reading sentence from user sentence = input("Enter sentence: ") # Finding longest word longest = max(sentence.split(), key=len) # Displaying longest word print("Longest word is: ", longest) print("And its length is: ", len(longest)) 

Output

Enter sentence: Tongue tied and twisted just an earth bound misfit I Longest word is: twisted And its length is: 7
  • Hello, World!
  • Add Two Numbers
  • Multiply Two Numbers
  • Celsius to Fahrenheit & Kelvin
  • Simple & Compound Interest
  • Rectangle Area & Perimeter
  • Area and Circumference of Circle
  • Calculate Area & Volume of Sphere
  • Area of Triangle
  • Area of an Ellipse
  • Area of Cone
  • Calculate Distance Between Two Points ( Co-ordinates)
  • Convert Cartesian to Polar Coordinate
  • Convert Polar to Cartesian Coordinate
  • Kilometer to Meter Conversion
  • Miles to Kilometers
  • Add Two Complex Number
  • Multiply Two Complex Number
  • Find Roots of a Quadratic Equation
  • Calculate Gravitational Force
  • Sum of First & Last Digit
  • Find ASCII Value
  • Days to Years, Months & Days Conversion
  • Calculate Monthly EMI
  • Check Leap Year
  • Even or Odd
  • Even or Odd Using Bitwise Operator
  • Even or Odd Using Conditional Operator
  • Largest of Two Numbers
  • Smallest of Two Numbers
  • Largest of Three Numbers
  • Smallest of Three Numbers
  • Calculate Value of PI Using Leibniz Formula
  • Validity of Triangle Given Sides
  • Validity of Triangle Given Angles
  • Check Triangle Types Given Sides
  • Python Program to Check Palindrome Number
  • Python Program to Check Prime Number
  • Python Program to Find Factorial of a Given Number
  • Python Program to Reverse a Given Number
  • Python Program to Calculate HCF (GCD) & LCM
  • Python Program to Calculate HCF (GCD) by Euclidean Algorithm
  • Python Program to Count Number of Digit
  • Python Program to Check Armstrong (Narcissistic) Number
  • Python Program to Check Whether a Number is Strong or Not
  • Python Program to Generate Fibonacci Series
  • Python Program to Check Perfect Number
  • Python Program to Check Triangular Number
  • Python Program to Check Co-Prime Numbers
  • Python Program to Check Automorphic (Cyclic) Number
  • Python Program to Generate Prime Numbers in Interval
  • Python Program to Generate Armstrong (Narcissistic) Number
  • Python Program to Generate Strong Numbers in an Interval
  • Python Program to Generate Perfect Numbers in an Interval
  • Generate Triangular Numbers in an Interval
  • Generate Automorphic (Cyclic) Numbers
  • Handsome Number Check
  • Harshad Number Check
  • Prime Factors
  • Powerful Number Check
  • Print Powerful Number in Range
  • Check Perfect Square
  • Divisors Of Given Number
  • Print Odd Numbers in Range
  • Print Even Numbers in Range
  • Multiplication Table of Number
  • Multiplication Table of 1 to 10
  • Types of Number
  • Sum of Digit of A Number
  • Sum of Digit of Number Until It Reduces To Single Digit
  • ASCII Table
  • Cartesian Product 2 Sets
  • Cartesian Product Multiple Sets
  • Generate Magic Square
  • Right Angle Triangle Star Pattern
  • Hollow Right Angle Triangle Pattern
  • Star Pyramid Pattern
  • Hollow Star Pyramid Pattern
  • Inverted Star Pyramid Pattern
  • 1-212-32123 Pattern
  • 1-121-12321 Pattern
  • Print 1-10-101-1010 Number Pattern
  • Print 0-01-010-0101 Binary Number Pattern
  • Print 1-101-10101 Binary Number Pyramid
  • Print 0-010-01010 Binary Number Pyramid
  • Flag of Nepal Using Star
  • Christmas Tree Pattern
  • Floyd’s Triangle
  • Plus Star Pattern
  • Cross Star Pattern
  • Asterisk Like Pattern
  • Diamond Pattern
  • Hollow Diamond Pattern
  • Pascal’s Triangle
  • Butterfly Pattern
  • 54321 5432 543 54 5 Pattern
  • 1 12 123 Pattern
  • 1 22 333 Pattern
  • a ab abc abcd Pattern
  • a bb ccc dddd pattern
  • A AB ABC ABCD Pattern
  • A BB CCC DDDD Pattern
  • A BAB CBABC Pattern
  • A ABA ABCBA Pattern
  • A ABC ABCDE Pattern
  • Hollow Square Pattern
  • Hollow Rectangular Pattern
  • Square Pattern
  • Rectangular Pattern
  • Hour-glass Pattern
  • Inverted Hollow Star Pyramid Pattern
  • Hollow Hour-glass Pattern
  • Plot Coordinates on a Plane
  • Sine Wave
  • Cos Wave
  • Sinc Function
  • Modified Bessel Function
  • Exponential Curve
  • Logarithmic Curve
  • Circle Plot
  • Heart Shape Plot
  • Plot Limacon
  • Plot Cardioid Curve
  • Plot Rose Curves
  • Plot Lemniscate Curve
Читайте также:  Html to pdf with itextsharp

Источник

Binary Study

In the program below, we read a string from user and find the longest word and it’s position in the string.

# Python program to read a String and Print Longest
# word and it's Position
# Read input string
str = input("Enter a String: ")
# Split the string to a list of words
word_list = str.split()
# Find the longest word
longest_word = max(word_list, key = len)
# Find the position (index) of longest word
pos = str.index(longest_word)
# Print the longest word and it's position
print("Longest word: ",longest_word)
print("Position of Longest word: ", pos)

Output

Enter a String: Binary Study Python programming made easy
Longest word: programming
Position of Longest word: 20

Program Explanation

We read the string from user using input() function. Assign the input string to str .

Then we create a list of words word_list using String split() method. The output of this method is a list. The string is split by the space.

Now we find max(word_list, key = len) function. It returns the longest element based on the length. Assign this to longest_word .

Now we apply String index() method passing longest_word as an argument . It returns the index of the first character of the longest_word . It is our desired position ( pos )of the longest word in the string. We could apply String find() method. It also returns the index of the first character of the passed sub string as parameter.

Finally print the longest word and it’s position.

Example (Using for Loop):

In the program below, the approach is same as the above. The only difference, we used for loop to find the longest words instead of using max() method.

str = input("Enter a String:")
words = str.split()
longest_word = words[0]
max_len = len(words[0])
for index, word in enumerate(words):
if len(word)> max_len:
max_len = len(word)
longest_word = word
else:
pass
idx = str.find(longest_word) # idx = str.index(longest_word)
print("Longest word: ",longest_word)
print("Position of Longest word: ", idx)
Enter a String: Binary Study Python programming made easy
Longest word: programming
Position of Longest word: 20

Notice the output of the two programs are the same. The second program is more naive in approach.

Читайте также:  По для расшифровки java

Methods and Functions Used

The following methods and functions are used in above two programs:

The input() Function

Here str is a string to show a default message before input.

It returns a string with value entered.

The String split() Method

str.split(separator, maxsplit)

Here separator specifies the separator to used, default is white space. The maxsplit specifies the number of split to do. Both the parameters are optional.

It returns a list. The words separated by white space are the list items.

>>> "Binary study programming made easy".split()
['Binary', 'study', 'programming', 'made', 'easy']

The max() Function

Here iterable can be any data type that is iterable such as list, tuple, dictionary, etc. The key is used to make comparison on that basis it returns the value. Here we used length ( len ) the basis of comparison.

>>> max(['Binary', 'study', 'programming', 'made', 'easy'], key = len)

'programming'

The String index() Method

Here substr is value to search for. As in our example substr is an individual word ( longest_word ).

It returns the index of first occurrence of the value of substr .

>>> "Binary study programming made easy".index('programming')
13

The len() Function

Here object is a sequence or collection. A string is a sequence of characters.

It returns the number of items in the object . (It returns number of characters.)

The String find() Method

Same as the string index() method. The only difference is that it returns -1 if the match is not successful while the index() method throws an exception.

>>> "Binary study programming made easy".find('programming') 13

You may be interest in the following articles-

Читайте также:  Open java file online

Further Reading:

Next Post:Important TorchVision Random Transforms used in Image Augmentation - Python PyTorch

Previous Post: How to get a image in video at particular time by using Python?

Источник

Python File I/O: Find the longest words

Flowchart: File I/O: Find the longest words.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

How to access environment variable values?

Environment variables are accessed through os.environ

import os print(os.environ['HOME'])

Or you can see a list of all the environment variables using:

As sometimes you might need to see a complete list!

# using get will return 'None' if a key is not present rather than raise a 'KeyError' print(os.environ.get('KEY_THAT_MIGHT_EXIST')) # os.getenv is equivalent, and can also give a default value instead of `None` print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Python default installation on Windows is C:\Python. If you want to find out while running python you can do:

import sys print(sys.prefix)
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью