Hướng dẫn fixed length string python

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.

This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
overwriteLine = False
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"

    prevOverwriteLine = consolePrinter.overwriteLine
    if prevOverwriteLine:
        #Previous line entry can be overwritten, so do so
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        #Previous line entry cannot be overwritten, take a new line
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    #Update the class variable for prevOverwriteLine
    consolePrinter.overwriteLine = overwriteThisLine

    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want this line to be overwriteable

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

View Discussion

Nội dung chính

  • Python len() Syntax
  • Python len() Example
  • Example 1: Len() function with tuples and string
  • Example 2: Python len() TypeError
  • Example 3: Python len() with dictionaries and sets
  • Example 4: Python len() with custom objects
  • Độ dài chuỗi trong python là gì
  • Tính độ dài chuỗi bằng hàm len trong python
  • Tổng kết

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Python len() function returns the length of the string. 

    Python len() Syntax

    Syntax: len(string) 

    Return: It returns an integer which is the length of the string. 

    Python len() Example

    len() methods with string in Python.

    Python3

    string = "Geeksforgeeks"

    print(len(string))

    Output:

    13

    Example 1: Len() function with tuples and string

    Here we are counting length of the tuples and list.

    Python

    tup = (1,2,3)

    print(len(tup))

    l = [1,2,3,4]

    print(len(l))

    Output: 

    3
    4

    Example 2: Python len() TypeError

    Python3

    Output:

    TypeError: object of type 'bool' has no len()

    Example 3: Python len() with dictionaries and sets

    Python3

    dic = {'a':1, 'b': 2}

    print(len(dic))

    s = { 1, 2, 3, 4}

    print(len(s))

    Output:

    2
    4

    Example 4: Python len() with custom objects

    Python3

    class Public:

        def __init__(self, number):

            self.number = number

        def __len__(self):

            return self.number

    obj = Public(12)

    print(len(obj))

    Output:

    12

    Time complexity : 

    len() function  has time complexity of O(1). in average and amortized case


    Hướng dẫn tính độ dài chuỗi trong python. Bạn sẽ học được cách tính độ dài chuỗi bằng cách sử dụng hàm len trong python sau bài viết này.

    Độ dài chuỗi trong python là gì

    Chúng ta coi độ dài chuỗi trong python chính là số ký tự tạo nên chuỗi đó.
    Ví dụ chuỗi bigcityboy được tạo bởi 10 ký tự, nên độ dài của chuỗi này bằng 10 đơn vị.
    Lưu ý rằng độ dài của chuỗi khác với index trong chuỗi, và index lớn nhất trong chuỗi chính bằng độ dài của chuỗi trừ đi 1 đơn vị.

    srt=`bigcityboy`


    Tính độ dài chuỗi bằng hàm len trong python

    Chúng ta sử dụng hàm len để tính độ dài chuỗi trong python.

    • Hàm len trong python là một hàm dựng sẵn giúp chúng ta đếm số ký tự trong đối số. Nếu chỉ định đối số này là một chuỗi, bạn sẽ đếm số ký tự chuỗi trong python. Nếu chỉ định đối số này là một list, bạn sẽ đếm số phần tử trong list python.

    Cú pháp sử dụng hàm len để tính độ dài chuỗi trong python như sau:

    len (str)

    Kết quả trả về sẽ là độ dài chuỗi str. Lưu ý kết quả của hàm len trong python là số ký tự có trong chuỗi chứ không phải là số bite có trong chuỗi, do đó kể cả các ký tự được tạo bởi 2 bite trở lên như tiếng Việt có dấu hay tiếng Nhật zenkaku, thì hàm len cũng đưa ra kết quả chính xác độ dài chuỗi trong python .

    Ví dụ:


    print(len('Hello'))



    print(len('Chào'))



    print(len('toukyo'))

    Mã mẫu

    Hãy cùng thực hành mã mẫu sau đây:

    print ("Số ký tự của chuỗi 'Hello' là " + str (len ("Hello")))



    print ("Số ký tự của chuỗi 'Việt Nam' là " + str (len ("Việt Nam")))


    Tổng kết

    Trên đây Kiyoshi đã hướng dẫn bạn cách tính độ dài chuỗi trong python bằng hàm len rồi. Để nắm rõ nội dung bài học hơn, bạn hãy thực hành viết lại các ví dụ của ngày hôm nay nhé.

    Và hãy cùng tìm hiểu những kiến thức sâu hơn về python trong các bài học tiếp theo.

    Viết bởi Kiyoshi. Đã đăng ký bản quyền tác giả tại <a title="Bạn được tự do chia sẻ bài viết nhưng phải để lại đường link bài viết từ laptrinhcanban.com. Bạn không được sử dụng tài liệu cho mục đích thương mại. Không được phép chỉnh sửa nội dung được phát hành trên website của chúng tôi" style="color:#fff;background-color:silver" rel="license noopener" target="_blank" href="https://creativecommons.org/licenses/by-nc-nd/4.0/">Creativecommons</a>&nbsp;và <a title="Bạn được tự do chia sẻ bài viết nhưng phải để lại đường link bài viết từ laptrinhcanban.com. Bạn không được sử dụng tài liệu cho mục đích thương mại. Không được phép chỉnh sửa nội dung được phát hành trên website của chúng tôi" style="color:#fff;background-color:silver" target="_blank" rel="noopener" href="https://www.dmca.com/Protection/Status.aspx?ID=1631afcd-7c4a-467d-8016-402c5073e5cd" class="dmca-badge">DMCA</a><script src="https://images.dmca.com/Badges/DMCABadgeHelper.min.js">

    Bài viết liên quan

    Hãy chia sẻ và cùng lan tỏa kiến thức lập trình Nhật Bản tại Việt Nam!

    HOME>> >>

    Profile
    Hướng dẫn fixed length string python

    Tác giả : Kiyoshi (Chis Thanh)

    Kiyoshi là một cựu du học sinh tại Nhật Bản. Sau khi tốt nghiệp đại học Toyama năm 2017, Kiyoshi hiện đang làm BrSE tại Tokyo, Nhật Bản.