使用 Python 找出截断句子后的 k 个分区
假设我们有句子 s,其中存在一些英语单词,这些单词由单个空格分隔,没有前导或后随空格。我们还有另一个值 k。我们必须找出截断后仅前 k 个单词。
因此,如果输入类似于 s = "Coding challenges are really helpful for students" k = 5,则输出将为 True (参见图像)
为了解决这个问题,我们将按照以下步骤操作 −
words := 以空格对 s 进行拆分
通过用空格分隔连接 words 数组中的前 k 个字母并返回
让我们看看以下实现以获得更好的理解 −
示例
def solve(s, k): words = s.split() return " ".join(words[:k]) s = "Coding challenges are really helpful for students" k = 5 print(solve(s, k))
输入
"Coding challenges are really helpful for students", 5
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
Coding challenges are really helpful
广告