Q:

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

belongs to collection: Python String Programs

0

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 )

String.split() Method

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".

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# 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 )

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Print EVEN length words... >>
<< Python program to print a string, extract characte...