Python | 程序以字符串长度打印单词
Given a string and we have to split the string into words and also print the length of the each word in Python.
給定一個(gè)字符串,我們必須將字符串拆分為單詞,并在Python中打印每個(gè)單詞的長(zhǎng)度。
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()方法 ,這是一個(gè)內(nèi)置方法 ,它通過給定的定界符將字符串拆分為子字符串(單詞)的集合。
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".
例如,有一個(gè)字符串str =“ ABC PQR XYZ” ,我們想通過使用空格將其拆分為多個(gè)單詞,那么此處的空格將成為定界符。 要將字符串拆分為單詞,該語句將為str.split(“”) ,然后輸出為“ ABC” “ PQR” “ XYZ” 。
Program:
程序:
# Function to split into words # and print words with its lengthdef splitString (str):# split the string by spacesstr = str.split (' ')# iterate words in stringfor 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
總結(jié)
以上是生活随笔為你收集整理的Python | 程序以字符串长度打印单词的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 杭州治少精无精最好的医院推荐
- 下一篇: 如何评价索尼Z5?