def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
**print LongestWord("Argument goes here")**
这行怎么了?我该如何更改?我听不懂!这让我真的很不舒服,因为在Coderbyte.com上说这是真的,而且可以正常工作!
答案 0 :(得分:1)
我不确定您也指的是哪一行?也许是最后一行。
如果是这样,则需要在python 3.x中带有print语句的括号
print(LongestWord("Argument goes here"))
此外,字符串转换在python 3中的工作方式有所不同
def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
intab ="~!@#$%^&*()-_+={}[]:;'<>?/,.|`"
trantab= str.maketrans(dict.fromkeys(intab))
sen = sen.translate(trantab)
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
print(LongestWord("Argument. 'Go' @goes here"))
答案 1 :(得分:1)
它工作正常,但没有返回尝试
print max(arr, key=len)
就像您直接在不带print关键字的情况下直接调用该函数一样,它不会显示最大值,或者您可以在一行中同时返回arr,max和打印函数输出,因此它看起来像这样:
def LongestWord(sen):
sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
arr = sen.split(" ")
print(arr)
print max(arr, key=len)
LongestWord("Argument goes here ! @")
注意:它适用于Python 2.7
如果您想使用PYTHON 3.7 使用以下
to_remove = sen.maketrans("", "", "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
sen = sen.translate(to_remove)