Hướng dẫn how do i limit the length of a string in python? - làm cách nào để giới hạn độ dài của một chuỗi trong python?

Giả sử rằng stryng là một chuỗi mà chúng ta muốn cắt ngắn và nchars là số lượng ký tự mong muốn trong chuỗi đầu ra.

stryng = "sadddddddddddddddddddddddddddddddddddddddddddddddddd"
nchars = 10

Chúng ta có thể cắt ngắn chuỗi như sau:

def truncate[stryng:str, nchars:int]:
    return [stryng[:nchars - 6] + " [...]"][:min[len[stryng], nchars]]

Kết quả cho một số trường hợp thử nghiệm nhất định được hiển thị dưới đây:

s = "sadddddddddddddddddddddddddddddd!"
s = "sa" + 30*"d" + "!"

truncate[s, 2]                ==  sa
truncate[s, 4]                ==  sadd
truncate[s, 10]               ==  sadd [...]
truncate[s, len[s]//2]        ==  sadddddddd [...]

Giải pháp của tôi tạo ra kết quả hợp lý cho các trường hợp thử nghiệm ở trên.

Tuy nhiên, một số trường hợp bệnh lý được hiển thị dưới đây:

Một số trường hợp bệnh lý!

truncate[s, len[s] - 3][]       ==  sadddddddddddddddddddddd [...]
truncate[s, len[s] - 2][]       ==  saddddddddddddddddddddddd [...]
truncate[s, len[s] - 1][]       ==  sadddddddddddddddddddddddd [...]
truncate[s, len[s] + 0][]       ==  saddddddddddddddddddddddddd [...]
truncate[s, len[s] + 1][]       ==  sadddddddddddddddddddddddddd [...
truncate[s, len[s] + 2][]       ==  saddddddddddddddddddddddddddd [..
truncate[s, len[s] + 3][]       ==  sadddddddddddddddddddddddddddd [.
truncate[s, len[s] + 4][]       ==  saddddddddddddddddddddddddddddd [
truncate[s, len[s] + 5][]       ==  sadddddddddddddddddddddddddddddd 
truncate[s, len[s] + 6][]       ==  sadddddddddddddddddddddddddddddd!
truncate[s, len[s] + 7][]       ==  sadddddddddddddddddddddddddddddd!
truncate[s, 9999][]             ==  sadddddddddddddddddddddddddddddd!

Notably,

  • Khi chuỗi chứa các ký tự dòng mới [
    def truncate[stryng:str, nchars:int]:
        return [stryng[:nchars - 6] + " [...]"][:min[len[stryng], nchars]]
    
    0], có thể có một vấn đề.
  • Khi
    def truncate[stryng:str, nchars:int]:
        return [stryng[:nchars - 6] + " [...]"][:min[len[stryng], nchars]]
    
    1, chúng ta nên in chuỗi
    def truncate[stryng:str, nchars:int]:
        return [stryng[:nchars - 6] + " [...]"][:min[len[stryng], nchars]]
    
    2 mà không cố gắng in "
    def truncate[stryng:str, nchars:int]:
        return [stryng[:nchars - 6] + " [...]"][:min[len[stryng], nchars]]
    
    3"

Dưới đây là một số mã khác:

import io

class truncate:
    """
        Example of Code Which Uses truncate:
        ```
            s = "\r"
            s = truncate[s, 10][]
            print[s]
                    ```
                Examples of Inputs and Outputs:
                        truncate[s, 2][]   ==  \r
                        truncate[s, 4][]   ==  \r

Bài Viết Liên Quan

Chủ Đề