python 我想使用sep="...”,但没有得到想要的结果

jc3wubiy  于 2023-02-18  发布在  Python
关注(0)|答案(4)|浏览(129)

我刚开始学习python。目前正在学习CS50p,想知道为什么我的代码不工作。我试图用(3)个句点替换空格,但我目前无法做到。

playback = input("Please write something that you'd like to see printed. Spaces will be replaced with 3 periods. ")  

print(playback, sep="...")

运行---〉输入:this is cs50p;预期产出:this...is...cs50p
当我运行这个程序时:

playback = input("Please write something that you'd like to print out. Spaces will be replaced with 3 periods. ")

print("hello,", playback, sep="...")

我得到hello,...this is cs50p
提前感谢您帮助!

wwtsj6pe

wwtsj6pe1#

以下是两个选项:

playback = input("Please write something that you'd like to see printed. Spaces will be replaced with 3 periods. ")  

print(*playback.split(), sep="...")
print(playback.replace(' ', '...'))

第一个选项可能更好,因为如果输入包含多个相邻空格,则第二个选项将产生您无法预料的结果

ev7lccsx

ev7lccsx2#

使用替换
打印(播放.替换(““,"...”))

tpxzln5u

tpxzln5u3#

有几种方法可以实现这一点。所有示例的假设输入都是"test test test"
第一个是字符串中的替换。

playback = input("Please write something that you'd like to print out. Spaces will be replaced with 3 periods. ")
print("hello,", playback.replace(" ", "..."), sep="...") 

Output:
hello,...test...test...test

请记住,这样,sep的唯一作用时间是在包含"hello,"playback之间,这将使空格替换为...
第二种是用刚刚分裂的

playback = input("Please write something that you'd like to print out. Spaces will be replaced with 3 periods. ")

print("hello,", *playback.split(" ") , sep="...") 

Output:
hello,...test...test...test

playback.split()前面的*split()返回的列表“打开”为多个输入,这就是sep参数可以对它起作用的方式。然而,我不认为使用*打开可迭代对象是您的课程在早期所涉及的内容。这是一个很好的例子,说明了print中的sep关键字是如何工作的。它接受传递给它的所有变量,并在每个变量之间添加传递给sep的字符串。由于*playback.split()打开为多个变量,sep可以作用于不同的字符串
我能想到的第三种方法是将splitjoin结合起来

playback = input("Please write something that you'd like to print out. Spaces will be replaced with 3 periods. ")

playback = playback.split(" ")
playback = "...".join(playback)

print("hello,", playback, sep="...")

Output:
hello,...test...test...test

同样,sep只在"hello,"playback上作为字符串运行,因为在拆分和合并之后,回放中已经有了...
您给出的“预期输出”在前面没有“hello”,因此您可以将其从print语句中删除。

ax6ht2ek

ax6ht2ek4#

仅打印的分隔符替换,
如果要将“”替换为...“”,请使用字符串替换。

>>> b = input("some input")
some input>? this is cs50p
>>> b
'this is cs50p'
>>> b.replace(' ', '...')
'this...is...cs50p'

这是我准则

相关问题