How to remove specific position characters from a string?

Asked

Viewed 13,897 times

1

I have a string read from a file that contains a data and the special new line character ' n'. Example:

dado = 'teste \n'

First I check the size of the string, then I can remove the last two characters, but how can I remove by pointing to the specific position of the character?

2 answers

8


Python strings, as in many other languages, are not changeable: that is, for any modification, Voce must create a new string (in general it is ok to associate the new string with the same variable).

Now, the "slices" syntax (Slices) from Python is extremely convenient for cropping, and pasting strings - just keep in mind that, as if it were a regua, the first slice dice, before the ":" is inclusive, and the ending is unique - this allows for practical things like:

dado = dado [0:4]  + dado[4:]  

Preserves the same string without duplicating any letter. (Cuts from start to position 4 - 0 could be omitted and then cuts from position 4 to the end - the omitted end allows you not to know the full length of the string)

So, to cut the letter from position [4] (in this case, the second "and"), you can write:

dado = dado[0:3] + dado[4:]

The syntax of indexes and slices also allows negative indexes - which count from the end of the string. Thus, empty is the end of the string, "-1" is the address of the last character, "-2" of the penultimate, and so on.

To cut the last two characters, just do:

dado = dado[:-2]

(cut from beginning to penultimate character position) You will hardly have such a case where you need to explicitly put the string size (returned by len(dado)) - and this avoids a lot of code that - in our heads is "direct", but keep typing, and looking at the code would be much more tiring than simply using negative indices.

0

For this, you can use the Slices.

In your case, it would look like this:

dado = dado[:5] # Pega do começo até a posição 5 - 1

Remembering that the strings are objects immutable, thus, it is not possible to remove a character: What you can do, in fact, re-assign to your variable a copy of string without the unwanted characters.

Browser other questions tagged

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