簡體   English   中英

如何在python中計算字符串的長度

[英]How to calculate the length of the string in python

您好,我是一名學生,我的代碼有一些錯誤,任何人都可以幫助我。 問題是輸入單詞和整數的列表,如果單詞的長度大於整數,則返回單詞。 這是我的答案。

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

我不確定是否需要檢查一個或多個單詞的長度,而只保留足夠長的單詞。 由於其他人回答了一個單詞,所以我回答了幾個單詞:

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']

U可以使用len()獲得任何字符串的長度

例:

print (len("string"))

結果:

6

這是一個簡單的示例:

在您的問題中,您說的指示是:

如果單詞的長度大於整數,則返回單詞。

下面的代碼可以做到這一點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM