一般计算字符串的数量,用len()方法就能实现,例如:
str="string"
len(str)
# 6(s,t,r,i,n,g)
但是,当要计算单词的数量时,该怎么办?
sentence = "hello , world and python"
len(sentence)
# 24
显然,不能直接用len(),它的结果包括了逗号“,“和空格“ ”。
提示:将字符串转变成列表
问题:一段消息里面的单词数计数。写一个函数,当单词数超过20个时,只显示前20个单词。
def num_word():
message_input = (input("message:"))
message = message_input.replace(',',' ')#用空格代替逗号
Message = message.split(' ')#将字符串转变为列表
if len(Message)<=20:
print(message_input)
else:
print(" ".join(Message[:20]) #"".join()将列表转为字符串
知识点:
字符串转变成列表:str.split()
str1 = "hi hello world"
print(str1.split(" "))
输出:
['hi', 'hello', 'world']
列表转变为字符串:"".join(list)
l = ["hi","hello","world"]
print(" ".join(l))
输出:
hi hello world
程序还有不完善的地方,请高手留言指教,谢谢!
更多有关python学习,请关注微信公众号:米斯特lu