我正在使用Python 2制作一个计算字符串字数和字母数的应用程序。

def string_length(aStr):
    number_of_words = len(aStr.split())
    number_of_letters = len(aStr)
    return number_of_words, number_of_letters

print string_length("my name is ahmed") #Returns (4, 16)


如何将(4,16)转换为:

4

16

最佳答案

由于string_length函数返回tuple,因此您必须在打印前打开包装。

def string_length(aStr):
    number_of_words = len(aStr.split())
    number_of_letters = len(aStr)
    return number_of_words, number_of_letters

# Unpacking the tuple
words, letters = string_length('my name is ahmed')

print words
print letters

10-01 10:54