Python | 程序以字符串长度打印单词

本文介绍如何在Python中将字符串拆分为单词并打印每个单词的长度。使用内置的split()方法,可以指定分隔符(如空格)来拆分字符串。示例代码展示了如何实现这一操作。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值