Hướng dẫn python add tab to every line - python thêm tab vào mọi dòng

Đối với tùy chọn linh hoạt, bạn có thể muốn xem TextWrap trong thư viện tiêu chuẩn.

Example:

>>> hamlet='''\
... To be, or not to be: that is the question:
... Whether 'tis nobler in the mind to suffer
... The slings and arrows of outrageous fortune,
... Or to take arms against a sea of troubles,
... And by opposing end them? To die: to sleep;
... No more; and by a sleep to say we end
... '''
>>> import textwrap
>>> wrapper=textwrap.TextWrapper(initial_indent='\t', subsequent_indent='\t'*2)
>>> print wrapper.fill(hamlet)
    To be, or not to be: that is the question: Whether 'tis nobler in the
        mind to suffer The slings and arrows of outrageous fortune, Or to
        take arms against a sea of troubles, And by opposing end them? To
        die: to sleep; No more; and by a sleep to say we end

Bạn có thể thấy rằng bạn không chỉ có thể dễ dàng thêm không gian linh hoạt ở mặt trước của mỗi dòng, bạn có thể cắt từng dòng để phù hợp, gạch nối, mở rộng tab, v.v.

Nó sẽ bao bọc (do đó tên) các dòng trở nên quá dài vì các bổ sung ở mặt trước:

>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end

Rất linh hoạt và hữu ích.

Chỉnh sửa

Nếu bạn muốn giữ ý nghĩa của các kết thúc dòng trong văn bản với TextWrap, chỉ cần kết hợp TextWrap với Splitlines để giữ các kết thúc dòng giống nhau.

Ví dụ về thụt lề treo:

import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 

bản in

Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.

Như Sato đã đề cập trong các bình luận, :help v_> sẽ cho thấy bạn giúp đỡ cho công cụ tốt nhất bạn có thể sử dụng cho việc này. >> ở chế độ bình thường sẽ thụt dòng dòng hiện tại;

>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end
0 sẽ thụt dòng dòng hiện tại và hai dòng sau;
>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end
1 sẽ giảm thụt lề.

Một tính năng khác hoạt động sẽ kết hợp với

>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end
2 có thể được tìm thấy tại
>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end
3. . Đối với mã Python,
>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3, 
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
            To be, or not to be: that is the
                question: Whether 'tis nobler in the
                mind to suffer The slings and arrows
                of outrageous fortune, Or to take
                arms against a sea of troubles, And
                by opposing end them? To die: to
                sleep; No more; and by a sleep to
                say we end
8 (thụt vào một đoạn) có thể hữu ích hơn, nhưng sử dụng chế độ trực quan để chọn các dòng như được mô tả trong :help v_> thậm chí còn dễ điều chỉnh hơn.

Đối với câu trả lời chung cho "Làm thế nào để thêm một ký tự/một số văn bản ở đầu mỗi dòng?" tức là, khi bạn muốn chèn một cái gì đó khác ngoài các tab hoặc không gian, có một vài cách:

import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
0 sẽ dự phòng
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
1 cho mọi dòng trong tệp.
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
2 có thể được thay thế bằng bất kỳ phạm vi nào bạn thích. (Xem
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
3 và cả
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
4)

Hoặc bạn có thể sử dụng ctrlvto vào chế độ trực quan theo chiều dọc, sử dụng

import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
5 và
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
6 để chọn một cột các ký tự, sau đó
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
7 (vốn) để chèn văn bản tại điểm đó trong tất cả các dòng được chọn. . (Xem
import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
8)

Thay đổi vết lõm của chuỗi đa dòng

Tín dụng: Tom tốt

Vấn đề

Bạn có một chuỗi được tạo thành từ nhiều dòng và bạn cần xây dựng một chuỗi khác từ nó, thêm hoặc loại bỏ các không gian hàng đầu trên mỗi dòng để vết lõm của mỗi dòng là một số khoảng trống tuyệt đối.

Dung dịch

Chúng tôi không cần

import textwrap

hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''

wrapper=textwrap.TextWrapper(initial_indent='\t'*1, 
                             subsequent_indent='\t'*3, 
                             width=30)

for para in hamlet.splitlines():
    print wrapper.fill(para)
    print 
9 cho việc này. Mô -đun
Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
0 (hoặc các phương thức chuỗi, trong Python 2.0 trở lên) là khá đủ:

import string
def reindent(s, numSpaces):
    s = string.split(s, '\n')
    s = [(numSpaces * ' ') + string.lstrip(line) for line in s]
    s = string.join(s, '\n')
    return s

Thảo luận

Khi làm việc với văn bản, có thể cần phải thay đổi mức thụt của một khối. Mã công thức này có một chuỗi đa dòng và thêm hoặc loại bỏ các không gian dẫn đầu trên mỗi dòng để mức thụt của mỗi dòng của khối phù hợp với một số không gian tuyệt đối. Ví dụ:

>>> x = """line one
... line two
... and line three
... """
>>> print x
line one
line two
and line three

>>> print reindent(x, 8)
        line one
        line two
        and line three

Ngay cả khi các dòng trong

Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
1 ban đầu được thụt vào khác nhau, công thức này làm cho vết lõm của chúng đồng nhất. Đây đôi khi là những gì chúng ta muốn, và đôi khi không. Một nhu cầu thường xuyên là điều chỉnh lượng không gian hàng đầu trong mỗi dòng, để sự thụt tương đối của mỗi dòng trong khối được bảo tồn. Điều này cũng không khó, đối với các giá trị tích cực hoặc âm của điều chỉnh. Tuy nhiên, các giá trị âm cần kiểm tra để đảm bảo rằng không có không gian không được đánh bắt từ đầu dòng. Do đó, chúng tôi cũng có thể chia chức năng thành hai chức năng để thực hiện các phép biến đổi, cộng với một chức năng để đo số lượng không gian hàng đầu của mỗi dòng và trả về kết quả dưới dạng danh sách:

def addSpaces(s, numAdd):
    white = " "*numAdd
    return white + white.join(s.splitlines(1))

def delSpaces(s, numDel):
    def aux(line, numDel=numDel, white=" "*numDel):
        if line[:numDel] != white:
            raise ValueError, "removing more spaces than there are!"
        return line[numDel:]
    return ''.join(map(aux, s.splitlines(1)))

def numSpaces(s):
    return [len(line)-len(line.lstrip()) for line in s.splitlines(  )]

Cách tiếp cận thay thế này dựa trên phương thức chuỗi

Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
2 (và do đó yêu cầu Python 2.0 trở lên, giống như bất kỳ công thức nào khác bằng các phương thức chuỗi và/hoặc danh sách toàn diện), tương tự như phân chia trên
Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
3 Trên mỗi dòng khi được gọi với một đối số thực sự. Điều này thường không quan trọng (ví dụ, tuyên bố cuối cùng trong ____34, có thể dễ dàng trả lại
Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
5), nhưng đôi khi hóa ra là (
Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
6 không thể ngắn và ngọt ngào nếu không có khả năng này của phương pháp chuỗi
Hamlet: In the secret parts
        of Fortune? O, most true!
        She is a strumpet. What's
        the news?

Rosencrantz: None, my lord,
        but that the world's grown
        honest.

Hamlet: Then is doomsday
        near.
2).

Ví dụ, ở đây, cách thức chúng ta có thể kết hợp các chức năng này để xây dựng một chức năng khác để xóa đủ các không gian dẫn đầu khỏi mỗi dòng để đảm bảo rằng đường thẳng của khối trở nên nhỏ nhất trở nên khó khăn, trong khi bảo tồn các vết lõm tương đối của tất cả các dòng khác:

def unIndentBlock(s):
    return delSpaces(s, min(numSpaces(s)))

Xem thêm

Phần tham chiếu thư viện về các loại trình tự.Library Reference section on sequence types.

Làm thế nào để bạn chèn một tab trong Python?

Trong các chuỗi Python, dấu gạch chéo ngược "\" là một nhân vật đặc biệt, còn được gọi là nhân vật "Escape".Nó được sử dụng để thể hiện các ký tự khoảng trắng nhất định: "\ t" là một tab, "\ n" là một dòng mới và "\ r" là một sự trở lại vận chuyển."\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

Làm thế nào để bạn in một không gian tab trong Python?

Làm cách nào để thêm một tab vào một bản in trong Python?Cách dễ nhất để in một ký tự tab trong Python là sử dụng chữ viết tắt ngắn '\ t'.Để xem ký tự khoảng cách tab trong việc đóng lại, bất kỳ biến nào chứa một ký tự tab trong hàm in tích hợp ().wrap any variable containing a tab character in the built-in print() function.