在Python中将长字符串换行换行的好方法是什么?

时间:2013-05-07 23:22:45

标签: python string python-3.x python-2.x

在我的项目中,我有一堆从文件中读入的字符串。在命令控制台中打印时,大多数都超过80个字符并且环绕,看起来很难看。

我希望能够让Python读取字符串,然后测试它是否超过75个字符。如果是,则将字符串拆分为多个字符串,然后在新行上逐个打印。 我也希望它聪明,不要切断全文。即"The quick brown <newline> fox..."而不是"the quick bro<newline>wn fox..."

我尝试修改类似的代码,在设定的长度后截断字符串,但只是删除字符串而不是将它放在一个新行中。

我可以用什么方法来实现这个目标?

7 个答案:

答案 0 :(得分:55)

您可以使用textwrap模块:

>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.
textwrap.fill上的

帮助

>>> textwrap.fill?

Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.

Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are expanded and other
whitespace characters converted to space.  See TextWrapper class for
available keyword args to customize wrapping behaviour.

如果您不想将某一行合并到另一行,请使用regex

import re


strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""

print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))

# Reading a single line at once:
for x in strs.splitlines():
    print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))

<强>输出:

In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.

答案 1 :(得分:11)

这是textwrap模块的用途。试试textwrap.fill(some_string, width=75)

答案 2 :(得分:4)

这类似于Ashwini的回答,但没有使用re

lim=75
for s in input_string.split("\n"):
    if s == "": print
    w=0 
    l = []
    for d in s.split():
        if w + len(d) + 1 <= lim:
            l.append(d)
            w += len(d) + 1 
        else:
            print " ".join(l)
            l = [d] 
            w = len(d)
    if (len(l)): print " ".join(l)
输入是您的问题时

输出

In my project, I have a bunch of strings that are read in from a file.
Most of them, when printed in the command console, exceed 80 characters in
length and wrap around, looking ugly.

I want to be able to have Python read the string, then test if it is over
75 characters in length. If it is, then split the string up into multiple
strings, then print one after the other on a new line. I also want it to be
smart, not cutting off full words. i.e. "The quick brown <newline> fox..."
instead of "the quick bro<newline>wn fox...".

答案 3 :(得分:0)

string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)

def wrap(string, max_width):
    s=''
    for i in range(0,len(string),max_width):
        s=s+string[i:i+max_width]
        s=s+'\n'
    return s

答案 4 :(得分:0)

string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)

def wrap(string, max_width):
    s=''
    for i in range(0,len(string),max_width):
        s+=string[i:i+max_width]
        s+='\n'
    return s

答案 5 :(得分:0)

在python-3

import textwrap
def wrap(string, max_width):
    return '\n'.join(textwrap.wrap(string,max_width))

输入:

wrap(ABCDEFGHIJKLIMNOQRSTUVWXYZ, 4)

输出:

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

答案 6 :(得分:0)

import pygame
from math import sin, cos, radians
pygame.init()

### PYGAME STUFF ######################################

SCREENWIDTH = 600
SCREENHEIGHT = 600
D = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
pygame.display.set_caption("PRESS SPACE TO ROTATE AROUND X")

######### MATH FUNCTIONS AND CLASSES ####################

class Mat3:
    # 3X3 MATRIX INITIALIZED WITH ALL 0's
    def __init__(self):
        self.matrix = [[0 for i in range(3)],
                      [0 for i in range(3)],
                      [0 for i in range(3)]]

class Vec2:
    # 2D VECTOR
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Vec3:
    #  3D VECTOR
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    def __add__(a, b):
        return Vec3(a.x+b.x, a.y+b.y, a.z+b.z)

def multVecMatrix(vec3, mat3):
    # MULTIPLIES A Vec3 OBJECT WITH Mat3 OBJECT AND RETURNS A NEW Vec3 
    x = vec3.x * mat3.matrix[0][0] + vec3.y * mat3.matrix[0][1] + vec3.z * mat3.matrix[0][2]
    y = vec3.x * mat3.matrix[1][0] + vec3.y * mat3.matrix[1][1] + vec3.z * mat3.matrix[1][2]
    z = vec3.x * mat3.matrix[2][0] + vec3.y * mat3.matrix[2][1] + vec3.z * mat3.matrix[2][2]
    return Vec3(x, y, z)

class Transform:
    # IT TRANSFORMS THE X AND Y FROM NORMALIZED SPACE TO SCREEN SPACE WITH PROJECTION APPLIED
    def worldSpaceTransform(self, vec3, w, h):
        if vec3.z == 0:
            vec3.z = 0.001
        zInverse = 1/ vec3.z
        xTransformed = ((vec3.x * zInverse) + 1) * (w/2)
        yTransformed = ((-vec3.y * zInverse) + 1) * (h/2)
        xTransformed = str(xTransformed)[:6]
        yTransformed = str(yTransformed)[:6]
        return Vec2(float(xTransformed), float(yTransformed))

class Rotation:
    def rotateX(self, theta):
        # ROTATION MATRIX IN X AXIS
        sinTheta = sin(theta)
        cosTheta = cos(theta)
        m = Mat3()
        m.matrix = [[1, 0,         0],
                    [0, cosTheta,  sinTheta],
                    [0, -sinTheta, cosTheta]]
        return m

    def rotate(self, vec3, theta, axis=None):
        # ROTATES A Vec3 BY GIVEN THETA AND AXIS
        if axis == "x":
            return multVecMatrix(vec3, self.rotateX(theta))
        if axis == "y":
            return multVecMatrix(vec3, self.rotateY(theta))
        if axis == "z":
            return multVecMatrix(vec3, self.rotateZ(theta))


transform = Transform()
rotation = Rotation()


# ASSIGNING 4 Vec3's FOR 4 SIDES OF SQUARE IN NORMALIZED SPACE
s = 1
modelPoints = [Vec3(-s, -s, -s), Vec3(s, -s, -s), Vec3(s, s, -s), Vec3(-s, s, -s)]

# TRANSLATING THE POINTS OF THE CUBE A LITTLE BIT INTO THE SCREEN
transVec = Vec3(0, 0, 6)

# ASSIGNING THE ROTATION ANGLES
thetax = 0

# APPLICATION LOOP
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    D.fill((255, 255, 255))

    # ROTATING THE POINTS AROUND X AXIS
    points = [rotation.rotate(pt, thetax, axis='x') for pt in modelPoints]

    # TRANSLATING THE POINTS OF THE CUBE A LITTLE BIT INTO THE SCREEN
    points = [pt + transVec for pt in points]

    # TRANSLATING THE SQUARE SHEET INTO THE SCREEN SPACE
    points = [transform.worldSpaceTransform(pt, SCREENWIDTH, SCREENHEIGHT) for pt in points]

    # STORING THE POINTS TO A TUPLE SO IT CAN BE DRAWN USING pygame.draw.lines
    points = [(pt.x, pt.y) for pt in points]
    
    keys = pygame.key.get_pressed()
    # ROTATE X ?
    if keys[pygame.K_SPACE]:
        thetax -= 0.005

    pygame.draw.lines(D, (0, 0, 0), True, points)
    
    pygame.display.flip()

输入: ABCDEFGHIJKLIMNOQRSTUVWXYZ“ \ n” 4

输出: ABCD“ \ n” EFGH“ \ n” IJKL“ \ n” IMNO“ \ n” QRST“ \ n” UVWX“ \ n” YZ“ \ n”