python - python 3中的字符串拆分格式

我正在尝试将此字符串格式化为一行包含五个单词的下方。但是,我一直将其作为输出:

I love cookies yes I do Let s see a dog

首先,我不是一行中有 5 个单词,而是一行中的所有内容。

其次,为什么“Let's”会 split ?我想在使用“单词”拆分字符串时,只有在中间有空格时才会拆分?

建议?

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)

最佳答案

首先,不要将变量称为“字符串”,因为它会影响 module同名

其次,使用 split()做你的分词

>>> s = """I love cookies. yes I do. Let's see a dog."""
>>> s.split()
['I', 'love', 'cookies.', 'yes', 'I', 'do.', "Let's", 'see', 'a', 'dog.']

来自 re-module

\W Matches any character which is not a Unicode word character. This is the opposite of \w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_] (but the flag affects the entire regular expression, so in such cases using an explicit [^a-zA-Z0-9_] may be a better choice).

由于上面没有列出',所以使用的正则表达式将“Let's”字符串分成两部分:

>>> words = re.split('\W+', s)
>>> words
['I', 'love', 'cookies', 'yes', 'I', 'do', 'Let', 's', 'see', 'a', 'dog', '']

这是我使用上面的 strip() 方法得到的输出:

$ ./sp3.py 
              I           love       cookies.            yes              I
            do.          Let's            see              a           dog.

代码可能会被简化为这样,因为 counter==0 和 else 子句做同样的事情。我通过 enumerate还有摆脱柜台:

#!/usr/bin/env python3

s = """I love cookies. yes I do. Let's see a dog."""
words = s.split()

output = ''
for n, i in enumerate(words):
    if n % 5 == 0:
        output += '\n'
    output += "{0:>15s}".format(i)
print(output)

https://stackoverflow.com/questions/17222355/

相关文章:

javascript - 并非所有浏览器都支持 toLocaleString()?

java - 如何在 IntelliJ 中停止流式 API 的扁平化

c++ - ostream showbase 不显示 "0x"为零值

java - 是否可以使用 String.format 作为条件小数点?

android - 在 EditText 中自动格式化电话号码

postgresql - 我可以在 PostgreSQL 中获得 CSV header 但没有行数吗

formatting - 如何使用 LaTeX 以实用程序员系列丛书的风格格式化源代码列表?

c# - microsoft.interop.excel 格式化单元格

ide - 为什么 IDE 不支持动态格式化?

io - Fortran 将我的输出添加到星号 - 为什么?