split a string of n into n chars, split() of n n

Asked

Viewed 479 times

5

I have the following text: "ola sou o Allan"

I would like to keep this text divided by e.g., 2-on-2 chars. How can I do this?

1 answer

5


Thus:

texto = "ola sou o Allan"
lista = [texto[i:i+2] for i in range(0, len(texto), 2)]

I took it from here.

Running:

>>> texto = "ola sou o Allan"
>>> lista = [texto[i:i+2] for i in range(0, len(texto), 2)]
>>> lista
['ol', 'a ', 'so', 'u ', 'o ', 'Al', 'la', 'n']

According to the answer in English, 2 may be variable:

>>> n = 2
>>> texto = "ola sou o Allan"
>>> lista = [texto[i:i+n] for i in range(0, len(texto), n)]
>>> lista
['ol', 'a ', 'so', 'u ', 'o ', 'Al', 'la', 'n']
  • 1

    There was a time when we wrote in Assembler. Then came the high-level languages. Now the languages are progressing so much that soon we will be writing in a language similar to the Assembler - difficult to read - only at a high level.

  • 1

    This Python construction to put for in an expression it is strange for those who come from outside the language, but it saves a lot of space in the program - and in the head of those who maintain it. It’s not very secret, though - it’s like a for normal, and the expression of the beginning whatever was in his body, adding elements to a list: res=[]; for i in range(0, len(texto), 2): res.append(texto[i: i + 2]) <- only that this normalemtne is in three lines and not in one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.