12

この文字列を、1 行に 5 語が含まれる以下の形式にしようとしています。ただし、出力としてこれを取得し続けます。

私はクッキーが大好きです はい、そうです 犬に会いましょう

まず、1 行に 5 語ではなく、すべてを 1 行にまとめています。

第二に、「Let's」が分裂するのはなぜですか? 「単語」を使用して文字列を分割すると、間にスペースがある場合にのみ分割されると思いましたか?

提案?

string = """I love cookies. yes I do. Let's see a dog."""


# split string
words = re.split('\W+',string)

words = [i for i in words if i != '']


counter = 0
output=''
for i in words:
    if counter == 0:
        output +="{0:>15s}".format(i)

# if counter == 5, new row
    elif counter % 5 == 0:
       output += '\n'
       output += "{0:>15s}".format(i)

    else:
       output += "{0:>15s}".format(i)

    # Increase the counter by 1
    counter += 1

print(output)
4

2 に答える 2

1
words = string.split()
while (len(words))
     for word in words[:5]
          print(word, end=" ")
     print()
     words = words[5:]

それが基本的な概念です。split() メソッドを使用して分割します

次に、スライス表記を使用してスライスし、最初の 5 単語を取得します

次に、最初の 5 単語を切り取り、もう一度ループします。

于 2013-06-20T19:45:15.167 に答える