Python使用sep="..."无法替换空格为三个句号的问题求助
问题原因及解决方法
你之前的代码没达到预期效果,核心是误解了print()函数中sep参数的作用:
sep仅用于指定print()里多个参数之间的分隔符,根本不会替换字符串内部的空格。- 第一段代码里
print(playback, sep="...")只有一个参数,sep完全没生效,自然不会改动原字符串的空格。 - 第二段代码里
sep只是把"hello,"和playback这两个参数用...分隔开,playback本身的空格还是原样保留。
正确解法:用字符串的replace()方法
要替换字符串内部的空格,得用Python字符串自带的replace()方法,它能精准替换字符串里指定的子串。
修正后的第一段代码(匹配你的初始需求):
playback = input("Please write something that you'd like to see printed. Spaces will be replaced with 3 periods. ") # 将原字符串中的空格替换为三个句号 formatted_text = playback.replace(" ", "...") print(formatted_text)
输入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. ") formatted_text = playback.replace(" ", "...") print("hello,", formatted_text, sep="...")
输入this is cs50p,会输出hello,...this...is...cs50p,既实现了参数间的分隔,也替换了原字符串内的空格。
内容的提问来源于stack exchange,提问作者one_day_
相关产品推荐
相关产品推荐

