我正试着要求玩家写一个句子。如果句子没有空格,它将返回原样。否则,我希望用下划线替换所有的空格。
sentence = input("Enter de sentence: ")
def replace():
if sentence.count(" ")>0:
sentence[1 : sentence.index(" ")] +"_"+ sentence[sentence.index(" ")+1 : len(sentence)]
else:
return replace()
print(replace)
print(replace)
不管我在“输入句子:”之后输入了什么,我都会得到这个回报:
<函数替换在0x7fecbc2b2280>
我已经尝试查找了一些代码的and,并试图更改一些变量,但都没有效果。
发布于 2022-11-03 10:12:14
你误解了很多东西,方法名称,变量,.
让我们回到一个简单的
def replace(content):
if content.count(" ") > 0:
content = content.replace(" ", "_")
return content
sentence = input("Enter de sentence: ")
print(replace(sentence))
但是这个例子太冗长了,只是为了解释它是如何工作的,实际上,您不需要检查是否有空格,只需使用str.replace
def no_space(content):
return content.replace(" ", "_")
sentence = input("Enter de sentence: ")
print(no_space(sentence))
发布于 2022-11-03 11:12:59
我只想提一下,所需的任务也可以这样完成:
我们使用.split()
方法分离输入文本。这将创建单个单词的列表。最后,我们需要使用带有下划线的'_'.join()
作为参数,将列表中的元素重新组合到最后的字符串。
这可以作为函数完成,也可以直接在代码中完成。
sentence = input().split()
print('_'.join(sentence))
发布于 2022-11-03 11:34:42
replace()
已经是字符串操作的内置方法.它将被简化为:
sentence = input("Enter de sentence: ").replace(' ','_')
print(sentence)
# Enter de sentence: I want to go to school
# I_want_to_go_to_school
但是,如果要创建自定义替换函数,则函数应该接收参数以传递输入字符串作为参数。在函数中,初始化一个新的空字符串来存储结果,然后使用for循环来迭代句子中的每个字符串。如果字符串是空格,则将其赋值为下划线和连接到新字符串。最后,返回新字符串。
sentence = input("Enter de sentence: ")
def replaces(sentence):
new = str()
for i in sentence:
if i == ' ':
i = '_'
new += i
else:
new += i
return new
print(replaces(sentence))
# Enter de sentence: I want to go to school
# I_want_to_go_to_school
https://stackoverflow.com/questions/74307724
复制相似问题