Después de tantos caracteres en una cadena, busque el espacio más cercano y colóquelo en una nueva línea

I'm trying to make everything look tidy in a file but I'm having a problem. I am asking for Details and if it is more then 27 bytes long then I need to find the nearest previous space and put it on a new line.

(using python 3.2)

I am starting with this:

Details = input ("Details: ")
delen = len(Details)
if delen >27:
    #Code Here
else:
    pass

Is this possible? If so could you give me a hand please?

¡Salud

preguntado el 09 de marzo de 12 a las 14:03

2 Respuestas

str.rfind es su amigo.

Details = input ("Details: ")
if len(Details) > 27:
    nearest_space = Details.rfind(' ', 0, 27)
    first, second = Details[:nearest_space], Details[nearest_space:]
else:
    first, second = Details, None

Tenga en cuenta que rfind will raise an exception if no space is found in Details.

respondido 10 mar '12, 19:03

That seems to work really well thank you. Only problem is is that the details string can some times be up to 100 chars long so will need to be split in to more then the two. is there anyway to do this please? - user1244772

I'm no Python expert. There are probably some fancy ways of doing this. I would keep it simple and do:

Detail = input ("Details: ")
line_length = 27
delen = len(Detail)
pos = 0
while pos < delen:
    print Detail[pos:pos+line_length]
    pos += line_length

respondido 09 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.