Given a string and we have to split the string into words and also print the length of the each word in Python.
給定一個字符串,我們必須將字符串拆分為單詞,并在Python中打印每個單詞的長度。
Example:
例:
Input:
str = "Hello World How are you?"
Output:
Hello ( 5 )
World ( 5 )
How ( 3 )
are ( 3 )
you? ( 4 )
String.split() Method
String.split()方法
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()方法 ,這是一個內置方法 ,它通過給定的定界符將字符串拆分為子字符串(單詞)的集合。
split() Method Syntax:
split()方法語法:
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".
例如,有一個字符串str =“ ABC PQR XYZ” ,我們想通過使用空格將其拆分為多個單詞,那么此處的空格將成為定界符。 要將字符串拆分為單詞,該語句將為str.split(“”) ,然后輸出為“ ABC” “ PQR” “ XYZ” 。
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 )
翻譯自: https://www.includehelp.com/python/print-words-with-their-length-of-a-string.aspx