我正在尝试将此字符串格式化为一行包含五个单词的下方。但是,我一直将其作为输出:
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)
我是一名优秀的程序员,十分优秀!