【问题标题】:how I can change whitespaces between words of a string in print order?如何按打印顺序更改字符串单词之间的空格?
【发布时间】:2022-11-28 02:18:17
【问题描述】:

我正在编写代码来输入用户的句子,然后将其空格更改为 ... 并打印该句子。

嗨岩石 我打算输入一个句子并将其空格更改为“...” 我写了这段代码:

    a=input("inter your sentence: ")
    #split in to n str
    #print every str with ... as whitespace
    a=a.split()
    for x in a:
        print(x, sep='...',end="")

如果我输入这是一个测验,我希望看到

这是一个测验

但它不起作用 它给了我

“这是一个测验

【问题讨论】:

  • 也许写a.replace(" ", "...")
  • 您是否阅读过 documentation 或对 sep 论点的工作原理进行过任何研究?仅打印时指定 sep 有何作用目的?

标签: python string printf


【解决方案1】:

做这个。

a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
print(*a, sep='...')

或者这样做。

a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split()
final_a = '...'.join(a)
print(final_a)

输出(用于输入this is test

this...is...test

【讨论】:

    【解决方案2】:

    str.replace 可用于将一个或多个具有相同 ASCII 值的字符替换为另一个。在您的情况下,它将是:

    a=input("inter your sentence: ")
    a=a.replace(' ', '...')
    print(a)
    

    【讨论】:

      【解决方案3】:

      在这种情况下,您可以使用 Python join 和 split 函数:

      inputSentence = input("Enter your sentence: ")
      
      print("...".join(inputSentence.split()))
      
      

      您可以使用下面的链接查看输出的屏幕截图

      https://i.stack.imgur.com/UOCGU.png

      【讨论】:

      • 不要附上屏幕截图,而是复制并粘贴程序的输出。
      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 2020-05-18
      • 2013-05-02
      相关资源
      最近更新 更多