【发布时间】:2015-11-28 01:23:21
【问题描述】:
我已经完成了这个程序的大约 80%,但我一生都无法弄清楚如何用星号替换元音并打印新字符串。
说明如下:
- 提示用户输入他/她的名字。
- 输出名称中的字母数。
- 打印名称中用空格分隔的所有字母,全部在一行上。
- 以大写形式打印名称。
- 使用一个切片从名称中创建一个新字符串,但不包含第一个和最后一个字母。
- 打印这个新字符串。
- 将原始名称传递给名为 str_func 的函数。
- 在 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