【问题标题】:How to truncate a string's length to the largest multiple of a smaller integer?如何将字符串的长度截断为较小整数的最大倍数?
【发布时间】:2016-04-07 23:34:44
【问题描述】:

我有一个任意长度的字符串path,以及一个小于或等于path 长度的整数x。我想将path 的长度截断为小于或等于path 原始长度的x 的最大倍数。

这是我能想到的最好的方法,但我觉得 Python 会有更好的方法来做到这一点:

final_length = 0
while final_length + x <= len(path):
    final_length = final_length + x
final_path = path[:final_length]

【问题讨论】:

    标签: python string truncate


    【解决方案1】:

    整数除法会在不使用循环的情况下给你想要的

    x = 3
    s = 'hello world'
    
    s[:(len(s) // x) * x]
    

    返回

    hello wor
    

    长度为 9

    【讨论】:

    • 可能做(稍微)更少工作的替代形式:s[:-(len(s) % x) or None]
    • 不错的@ShadowRanger!
    • 谢谢!我知道有一种更优雅的方法可以做到这一点,但我无法完全确定它。
    猜你喜欢
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多