Python | Program to print words with their length of a string

Here, we will learn how to print the length of the words from a string in Python? To extract the words from the string, we will use String.split() method and to get word’s length, we will use len() method.
Submitted by IncludeHelp, on July 27, 2018

Problem statement

Given a string and we have to split the string into words and also print the length of the each word in Python.

Example

Input:
str = "Hello World How are you?"

Output:
Hello ( 5 )
World ( 5 )
How ( 3 )
are ( 3 )
you? ( 4 )

Split words and print their length of a string

To split string into words, we use split() method, it is an inbuilt method which splits the string into set of sub-string (words) by given delimiter.

split() Method Syntax:

 String.split(delimiter)

Explanation:

For example, there is a string str = "ABC PQR XYZ" and we want to split into words by separating it using space, then space will be delimiter here. To split the string to words, the statement will be str.split(" ") and then output will be "ABC" "PQR" "XYZ".

Python program to print words with their length of a string

# Function to split into words
# and print words with its length

def splitString(str):
    # split the string by spaces
    str = str.split(" ")
    # iterate words in string
    for words in str:
        print(words, " (", len(words), ")")

# Main code
# declare string and assign value
str = "Hello World How are you?"

# call the function
splitString(str)

Output

Hello  ( 5 )
World  ( 5 )
How  ( 3 )
are  ( 3 )
you?  ( 4 )

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.