How to remove specific position characters from a string?

1

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

dado = 'teste \n'

First check the string size, so I can remove the last two characters, but how can I remove pointing to the character's specific position?

    
asked by anonymous 29.01.2018 / 13:20

2 answers

5

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

Now the Python slice syntax is extremely convenient for trimming, and pasting strings - just keep in mind that, as if it were a rule, the first index of the slice, before the ":" is inclusive, and the end is unique - this allows for very practical things like:

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

Preserves the same string without duplicating any letters. (Cut from start to position 4 - 0 could be omitted and then cut from position 4 to the end - the omitted end lets you not know the full size of the string)

So, to cut the letter of the position [4] (in this case, the second "e"), 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. So 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 the beginning to the position of the penultimate character) You will hardly have a case like this where you need to explicitly place the string size (returned by len(dado) ) - and this avoids a lot of code that - in the head of people is "straight", but typing, and looking in the code would be much more tiring than simply using negative indexes.

    
29.01.2018 / 13:31
0

To do this, you can use slices .

In your case, it would look like this:

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

Remembering that strings are immutable a>, so you can not remove a character: What you can actually do is re-assign a copy of string to your variable without the unwanted characters.

    
29.01.2018 / 13:31