博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python | 程序以字符串长度打印单词
阅读量:2531 次
发布时间:2019-05-11

本文共 1432 字,大约阅读时间需要 4 分钟。

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 lengthdef 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 functionsplitString(str)

Output

输出量

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

翻译自:

转载地址:http://gyazd.baihongyu.com/

你可能感兴趣的文章
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>
MySQL存储过程定时任务
查看>>
Python中and(逻辑与)计算法则
查看>>
POJ 3267 The Cow Lexicon(动态规划)
查看>>
设计原理+设计模式
查看>>
音视频处理
查看>>
tomcat 7服务器跨域问题解决
查看>>
前台实现ajax 需注意的地方
查看>>
Jenkins安装配置
查看>>
个人工作总结05(第二阶段)
查看>>
Java clone() 浅拷贝 深拷贝
查看>>