sentence = "This is my sentence"
# split the sentence
words = sentence.split()
# use len() to obtain the number of elements (words) in the list words
print('There are {} words in the given sentence'.format(len(words)))
# go through each word
for word in words:
# len() counts the number of elements again,
# but this time it's the chars in the string
print('There are {} characters in the word "{}"'.format(len(word), word))
# python is a 0-based language, in the sense that the first element is indexed at 0
# you can go backward in an array too using negative indices.
#
# However, notice that the last element is at -1 and second to last is -2,
# it can be a little bit confusing at the beginning when we know that the second
# element from the start is indexed at 1 and not 2.
print('The first being "{}" and the last "{}"'.format(word[0], word[-1]))
import re
def count_letter(word):
"""(str) -> int
Return the number of letters in a word.
>>> count_letter('cat')
3
>>> count_letter('cat1')
3
"""
return len(re.findall('[a-zA-Z]', word))
if __name__ == '__main__':
sentence = input('Please enter your sentence: ')
words = re.sub("[^\w]", " ", sentence).split()
# The number of characters in the sentence.
print(len(sentence))
# The number of words in the sentence.
print(len(words))
# Print all the words in the sentence, the number of letters, the first
# and last letter.
for i in words:
print(i, count_letter(i), i[0], i[-1])
Please enter your sentence: hello user
10
2
hello 5 h o
user 4 u r
请阅读Python的字符串文档,它是不言而喻的。以下是对不同部分的简短解释和一些评论。在
我们知道一个句子是由单词组成的,每个单词都是由字母组成的。我们首先要做的是把这个句子变成单词。这个列表中的每个条目都是一个单词,每个单词都以一系列字符的形式存储,我们可以得到每个单词。在
我们不会为你做堆栈溢出的作业。。。但我会让你开始的。在
您将需要以下两种方法中的一种(取决于python的版本):
input([prompt])
,。。如果提示参数存在,则写入 没有尾随换行符的标准输出。那么函数呢 从输入中读取行,将其转换为字符串(剥离 并返回。当读取EOF时,EOFError为 提高。http://docs.python.org/3/library/functions.html#inputraw_input([prompt])
,。。。如果提示参数是 现在,它被写入标准输出,不带尾随换行符。 然后,该函数从输入中读取一行,并将其转换为字符串 (去掉尾随的换行符),并返回该值。当读取EOF时, EOFError升高。http://docs.python.org/2.7/library/functions.html#raw_input你可以像这样使用它们
如您所见,写入的文本是在
my_sentance
变量中存储的要获得字符串中的字符数,您需要了解字符串实际上只是一个列表!因此,如果您想知道可以使用的字符数量:
len(s)
,。。。返回对象的长度(项数)。 参数可以是序列(字符串、元组或列表)或映射 (字典)。http://docs.python.org/3/library/functions.html#len我让你想想怎么用它。
最后,需要为字符串使用内置函数:
str.split([sep[, maxsplit]])
,…返回 使用sep字符串作为分隔符。如果给定maxsplit,则在 大多数maxplit拆分都已完成(因此,列表最多 最大分割+1个元素)。如果未指定-1,则为-1 对拆分的数量没有限制(所有可能的拆分都会进行)。 http://docs.python.org/2/library/stdtypes.html#str.split我希望您慢慢来,了解下面的代码是怎么回事,我建议您阅读这些参考资料。在
http://docs.python.org/3/library/re.html
http://docs.python.org/3/library/functions.html#len
http://docs.python.org/3/library/functions.html
http://docs.python.org/3/library/stdtypes.html#str.split
相关问题 更多 >
编程相关推荐