您可以使用len()获取任何字符串的长度
示例:print (len("string"))
结果:6
下面是一个简单的例子:
在你的问题中,你说指示是:return the words if the length of the words is more than the integer.
下面的代码将执行此操作:my_str = raw_input("Enter a word: ")
n = raw_input("Enter an integer: ")
def filter_long_words(my_str, n):
if len(my_str) > int(n):
return my_str # assigns the results of my_string to some_word
some_word = filter_long_words(my_str, n)
print some_word
针对您在评论中提出的问题:def filter_long_words():
my_str = raw_input("Enter a word: ")
n = raw_input("Enter an integer: ")
if len(my_str) > int(n):
return my_str # assigns the results of my_string to some_word
some_word = filter_long_words()
print some_word
最后一个例子。假设您将几个单词作为一个大字符串输入。
我们可以使用.split()来获取每个单词并分别进行测试。# simulates raw input of 4 words being typed in at once.
list_of_words_as_a_string = "One Two Three Four"
n = raw_input("Enter an integer: ")
def filter_long_words(word, n):
if len(word) > int(n):
print word
return word # this is only useful if you are doing something with the returned word.
for word in list_of_words_as_a_string.split():
filter_long_words(word, n)
使用3作为整数时的结果:Enter an integer: 3
Three
Four