将字符串添加到空字符串时出错

2024-03-29 06:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序有一个问题,该程序应该使用一个函数来反转字符串,该函数取字符串的第一个字,而该函数打印字符串时不带第一个字。你知道吗

def first_word(string):
    first_space_pos = string.find(" ")
    word = string[0:first_space_pos]
    print(word)

def last_words(string):
    first_space_pos = string.find(" ")
    words = string[first_space_pos+1:]
    print(words)

def reverse(string):
    words = string.count(" ") +1
    count = 1
    string_reversed = ""
    while count < words:
        string_reversed = first_word(string) + str(" ") + string_reversed
        string = last_words(string)
        count += 1
    print(string_reversed)

我得到的错误是:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

这句话的意思是:

string_reversed = first_word(string) + str(" ") + string_reversed

感谢您的帮助。谢谢。你知道吗


Tags: 函数字符串pos程序stringdefcountspace
3条回答

您混淆了printreturn的功能。你知道吗

print是一个python函数,如果显式指定,它将把括号中的内容打印到stdout或其他输出流中。你知道吗

return是将所需内容作为函数值发送回来的语句。你知道吗

即:

>>> def foo():
    print('foo')


>>> def bar():
    return 'bar'

>>> u = foo()
foo
>>> u
>>> type(u)
<class 'NoneType'>
>>> u = bar()
>>> u
'bar'
>>> type(u)
<class 'str'>

此外,您可以使用python str[::-1]做您想做的事情

>>> def stringReverse(s):
    print(' '.join(s.split()[::-1]))


>>> stringReverse('Hello this is how to reverse a string')
string a reverse to how is this Hello

不过,这只是一个建议,因为您可能正试图以特定的方式进行字符串反转。正如Prune所说,如果您用return替换print,那么您的函数工作得非常好

您混淆了打印返回打印将值转储到输出(您的屏幕),但不会更改内存中的任何数据,也不会对该值做任何进一步的操作。返回将其作为函数值返回。你知道吗

正如编译器警告告诉我的那样,没有一个函数向调用者返回任何值。因此,您得到“None”作为值,并且您的调用程序会出错。用return替换所有的terminalprint语句,代码运行良好:

def first_word(string):
    first_space_pos = string.find(" ")
    word = string[0:first_space_pos]
    return word

def last_words(string):
    first_space_pos = string.find(" ")
    words = string[first_space_pos+1:]
    return words

def reverse(string):
    words = string.count(" ") +1
    count = 1
    string_reversed = ""
    while count < words:
        string_reversed = first_word(string) + str(" ") + string_reversed
        string = last_words(string)
        count += 1
    return string_reversed

print reverse("Now is the time for all good parties to come to the aid of man.")

输出:

of aid the to come to parties good all for time the is Now 

first_word不返回任何内容,因此生成None值,不能用作带字符串的+操作数。可能您想返回word。你知道吗

相关问题 更多 >