为什么 truncated-at-n-chars 在 Python 中意味着 n - 3?

编辑:我什至没有想到“...”是 n 的一部分。对不起大家!(谢谢)


我不确定“问题”是否遗漏了什么,或者我是否遗漏了什么。我应该在 python 中编写一个函数,该函数返回截断的 n-chars 版本的短语。文档字符串如下:


"""Return truncated-at-n-chars version of phrase.


If the phrase is longer than n, make sure it ends with '...' and is no

longer than n.


    >>> truncate("Hello World", 6)

    'Hel...'


    >>> truncate("Problem solving is the best!", 10)

    'Problem...'


    >>> truncate("Yo", 100)

    'Yo'


The smallest legal value of n is 3; if less, return a message:


    >>> truncate('Cool', 1)

    'Truncation must be at least 3 characters.'


    >>> truncate("Woah", 4)

    'W...'


    >>> truncate("Woah", 3)

    '...'

"""

解决方案是:


if n < 3:

    return "Truncation must be at least 3 characters."


if n > len(phrase) + 2:

    return phrase


return phrase[:n - 3] + "..."

那为什么是n-3呢?是因为它说“n的最小合法值是3”吗?因为当我用谷歌搜索时,可能少于 3 个。即使不是,为什么它不直接返回 phrase[:n] + "..."?


子衿沉夜
浏览 61回答 1
1回答

心有法竹

解决方案包含 n-3 的原因是因为您必须确保从末尾保留 3 个字符,以便您可以添加“...”。例如,如果您有单词“Elephant”并且您必须将其截断为 5 个字符。输入看起来像这样truncate("Elephant",&nbsp;5)输出看起来像这样'El...'如您所见,我没有使用单词“Elephant”的前 5 个字符,而是仅使用前 2 个字符,因为每个点 (.) 也算作一个字符,所以我必须从 n 中减去 3 来计算每个字符点 (.) 也是如此。希望这能回答您的问题!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python