【问题标题】:Why can't I return the modified str_func function back to the main function?为什么我不能将修改后的 str_func 函数返回给主函数?
【发布时间】:2015-11-28 01:23:21
【问题描述】:

我已经完成了这个程序的大约 80%,但我一生都无法弄清楚如何用星号替换元音并打印新字符串。

说明如下:

  1. 提示用户输入他/她的名字。
  2. 输出名称中的字母数。
  3. 打印名称中用空格分隔的所有字母,全部在一行上。
  4. 以大写形式打印名称。
  5. 使用一个切片从名称中创建一个新字符串,但不包含第一个和最后一个字母。
  6. 打印这个新字符串。
  7. 将原始名称传递给名为 str_func 的函数。
  8. 在 str_func 函数内部:
    • 用星号替换名称中的元音
    • 将修改后的名称返回给 main
    • 回到main,打印str_func返回的字符串。

到目前为止我的代码:

def main():

    name = input('Enter your first name: ')

    print(name)

    ### print name with spaces in between characters
    spaces = ''
    for ch in name:
        spaces = spaces + ch + ' '
    print(spaces[:-1]) # to get rid of space after e

    print('name in caps is,',name.upper())  # print name in all caps

    print('After chopping the name we get',name[1:4])

    print(str_func)

def str_func():

    str_func = name.replace('a','*')
    return str_func



main()

我的一个朋友帮助我说我的 str_func 函数有问题:

该函数应该在调用时将名称作为主函数中的参数。 你不打印它。你叫它,像这样: new_name = str_func(name)

像这样定义 str_func()。我给你加了一些伪代码。

def str_func(name):
       ###make a string containing the vowels
       ###loop through the name
       ###replace vowel if found with *
       ### after loop, return the name

请帮忙!!

【问题讨论】:

  • 你在 str_func 内部重新定义了 str_func
  • 你朋友的伪代码建议不错。你了解他们吗?您了解函数及其参数的工作原理吗? StackOverflow 不是来帮你做功课的(尽管你可能会很幸运,无论如何都会有人回答)。您需要就您遇到的问题向我们提出具体问题,而不仅仅是“我卡住了,求助”。
  • 请注意,您正在使用name[1:4] 对字符串进行切片。您确定输入的长度始终为 5 个字符吗?
  • 对于这个特定的示例,我将保持名称始终为 5 个字符长。 Blckknght 我非常清楚这不仅仅是为了让学生完成他们的家庭作业,我真的在努力学习这门语言,而上周的作业是到期的。我知道我应该将新字符串传递回 main 但不明白为什么我的代码不起作用。我会做得更好,以确保它看起来不像我只是在将来寻求帮助!
  • 希望这个解释会有所帮助,您的代码不会调用您在 main() 函数下方定义的函数 str_func()print(str_func) 行应该给出了一个 NameError 未定义名称“str_func”。

标签: python string function replace


【解决方案1】:

其他人已经为您的直接问题提供了解决方案,但我会尝试改进整个代码。我不知道你被介绍过哪些功能,所以我可能会为每个步骤提供一个简单的实现和 Python 式的实现。

  • 首先,您没有回答问题 2:打印输入字符串的长度。您可以手动计算它们:

    size = 0
    for letter in name:
        size += 1
    print(size)
    

    或者使用内置函数len

    size = len(name)
    print(size) # or print(len(name)) if you don't need the intermediate variable
    
  • 您可以使用字符串的join 方法改进输入的间距:

    spaced = ' '.join(name)
    print(spaced) # or print(' '.join(name)) if you don't need spaced
    

    您可以将任何可迭代的字符串传递给join,并且字符串适合。

  • 您的切片采用您输入的第二个、第三个和第四个字母。不管它的长度是多少。您需要使用之前计算的字符串的长度:

    sliced = name[1:size-1]
    print(sliced)
    

    或在切片符号中使用负数从字符串末尾开始计数:

    print(name[1:-1])
    
  • 您需要编写一个函数并调用它来改变字符串。因此,您必须这样称呼它:

    mutated = str_func(name)
    print(mutated)
    

    该函数可以遍历原始字符串:

    def str_func(original):
        copy = ''
        for letter in original:
            if letter in 'auieoy':
                copy += '*'
            else:
                copy += letter
        return copy
    

    或使用replace:

    def str_func(original):
        copy = original
        for vowel in 'aeuioy':
            copy = copy.replace(vowel, '*')
        return copy
    

    您甚至可以使用translate,它更适合更一般的用途:

    def str_func(original):
        from string import maketrans
        vowels = 'auieoy'
        return original.translate(maketrans(vowels, '*' * len(vowels)))
    

将所有这些组装在一起:

from string import maketrans

def do_stuff():
    name = input('Enter your first name: ')
    print('Your input is', name)
    print('It\'s length is', len(name))
    print('Adding spaces:', ' '.join(name))
    print('Capitalizing it:', name.upper())
    print('Chopping it:', name[1:-1])
    mutated = str_func(name)
    print('Removing vowels:', mutated)

def str_func(original):
    vowels = 'auieoy'
    return original.translate(maketrans(vowels, '*' * len(vowels)))

if __name__ == '__main__':
    do_stuff()

【讨论】:

    【解决方案2】:

    这可能会对你有所帮助。

    import re
    def main():
        #Using "raw_input" instead of "input"
        name = raw_input('Enter your first name: ')
    
        print(name)
    
        ### print name with spaces in between characters
        spaces = ''
        for ch in name:
            spaces = spaces + ch + ' '
        print(spaces[:-1]) # to get rid of space after e
    
        print('name in caps is,',name.upper())  # print name in all caps
    
        print('After chopping the name we get',name[1:4])
    
        new_name=str_func(name)
        print(new_name)
    
    def str_func(value):
        #re is regular expression module. It will match string "Guido" and re.IGNORECASE makes it case insensitive.
        #When value will Guido, it will be returned as it is.
        if re.match(r"Guido",value,re.IGNORECASE):
            return value
        else:
            for x in "aeiou":
                value= value.replace(x, '*')
            return value
    
    main()
    

    输出

    C:\Users\Dinesh Pundkar\Desktop>python a.py
    Enter your first name: Guido
    Guido
    G u i d o
    ('name in caps is,', 'GUIDO')
    ('After chopping the name we get', 'uid')
    Guido
    
    C:\Users\Dinesh Pundkar\Desktop>python a.py
    Enter your first name: Jfalcone
    Jfalcone
    J f a l c o n e
    ('name in caps is,', 'JFALCONE')
    ('After chopping the name we get', 'fal')
    Jf*lc*n*
    
    C:\Users\Dinesh Pundkar\Desktop>
    

    【讨论】:

    • 这个名字本来应该保留 Guido,但非常感谢 Dinesh 提供了更好看的程序,这肯定会派上用场,因为我仍然掌握在函数中定义函数并返回它们的窍门!非常感谢
    • @Jfalcone - 但是在伪代码中你提到元音应该被*替换。
    • 元音应该被替换为yes,但是为了这个例子的目的,guido这个名字应该是一样的。 (在上面的程序中也不能调用 print 函数)
    • print new_name 需要是 print(new_name) 并且原始输入不起作用。起飞 raw_ 并且它可以工作 90%,但不会用星号替换元音。爱你仍然试图让它工作!总是很高兴看到程序员有多么坚定
    • @Jfalcone 将 print new_name 更改为 print(new_name)。在我的情况下一切正常。您可以查看我粘贴的演示输出。对于哪个单词,元音不会被 * 取代?请粘贴输出。
    【解决方案3】:
    test = 'qwertyuiopasdfghjklzxcvbnm'
    
    def changestring(string):
        for x in 'aeiou':
            string = string.replace(x, '*')
        return string
    
    changestring(test)
    'qw*rty***p*sdfghjklzxcvbnm'
    

    这是你想要做的吗?

    【讨论】:

    • 为什么要为元音创建一个列表,字符串也是可迭代的:for x in 'auieo'.
    • 是的,我相信!我会尝试将这些步骤纳入其中,看看我能否最终让这个程序正常工作,谢谢 Nils!
    • Nils 我非常感谢您的快速帮助,在 Guido 单词更改为 G*d 之前我仍然收到错误消息,但除此之外,程序是成功!对所有帮助我们新程序员的人的巨大信任
    • @Jfalcone - 你得到同样的错误吗?还是别的什么?
    • 是我在 G*d 之前收到的错误,在“切碎之后我们得到 uid”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2019-09-13
    • 2019-01-08
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多