【问题标题】:How to add a space between a string for every 5th letter? [duplicate]如何在每个第 5 个字母的字符串之间添加一个空格? [复制]
【发布时间】:2014-05-13 06:13:37
【问题描述】:

嘿,在计算机询问他们想要多少硬币之后,我正试图弄清楚如何在我的程序中每五个字母之间输入一个空格。所以这就是它目前的样子。

pile1_str = "pile 1: "
x="O"
y=1
while y <= pile1:   #pile1 being the number of chips the user inputs     
    pile1_str = pile1_str + x
    print(pile1_str)
    y= y+1

输入 12 个硬币时应该是这样的:

pile 1: OOOOO OOOOO OO

如何在字符串中的每个第 n (5) 个字符后插入一个空格?

【问题讨论】:

  • 那么问题出在哪里?
  • @alKid 谢谢,我会试试的。

标签: python


【解决方案1】:
pile1_str = "pile 1: "
x="O"
y=1
while y <= pile1:
    pile1_str = pile1_str + x
    if y%1==0:
        pile1_str = pile1_str + " "
    print(pile1_str)
    y= y+1

【讨论】:

    【解决方案2】:
    length = 19
    groupSize = 5
    pile = 'O' * length
    spacedPile = ' '.join(pile[i:i+groupSize] for i in xrange(0, len(pile), groupSize))
    print spacedPile
    

    【讨论】:

    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of howwhy 这解决了问题。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多