如何计算python中字符串的长度

How to calculate the length of the string in python

你好,我是一名学生,我的代码有一些错误,任何人都可以帮助我。 问题是输入单词列表和整数,如果单词的长度大于整数,则return单词。 这是我的答案。

def filter_long_words(string):
string = raw_input("Enter a words : ")
n = raw_input("Enter an integer : ")

count = 0
for letter in string:
    count = count + 1
print "The total string are : ", count

return count 

filter_long_words(string)
if count > n:
    print string

U可以用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

你可以用len()

得到一个字符串的长度
string = raw_input("Enter a words : ")
n = int(raw_input("Enter an integer : ")) # convert the input to integer

if len(string) > n :
    print(string)

您可以使用len函数来获取字符串的长度。

def filter_long_words():
  string = raw_input("Enter a words : ")
  n = raw_input("Enter an integer : ")

  print ("The total string are : ", len(string))
  if len(string) > int(n):
    return string

我不知道你是否需要检查一个单词或几个单词的长度并且只保留足够长的单词。既然别人回答一个字,我就回答几个字:

string = raw_input("Enter several words: ")
n = int(raw_input("Enter an integer: "))


def filter_long_words(string, n):
    long_words = [word for word in string.split() if len(word) > n]
    return long_words

print filter_long_words(string, n)

因此,如果 string = 'one two three four five six'n = 3,输出将是 ['three', 'four', 'five']

求字符串的长度而不计算空格

def StrLx_(my_str):
    #I am defining a function here for it if you don't want it you can 
    #delete this part
      
    space = " "  
    no_space = ""  
    a = 0

    for char in my_str:
        if char not in space:
            no_space = no_space + char

    string = no_space

    while string[a] != string[-1]:
        a = a+1
    
    print(a+1)

计算空格的字符串长度

def StrL_(my_str):
    #lly here

    a = 0
    
    while my_str[0] != my_str[-1]:
        a = a+1
    
    print(a+1)