If you are reading from a txt as you say the problem, it may be that the last character is a line jump '\ n' or carriage return \r
and you are not deleting it. It is not an empty character but '\ n' or \r
.
If we have the following txt called datos.txt
as an example:
the red car.house
the blue car.garage
If we read it this way:
data = open('datos.txt')
print('Imprimiendo última letra de cada línea:')
for cadenaaux in data:
print(cadenaaux[-1])
data.close()
The output is:
Imprimiendo última letra de cada línea:
e
In this case the first string, if it is a file with the purpose of Windows style line, is actually:
the red car.house \ r \ n
This causes us to print a line break (the other is due to print
).
To avoid this, what is done is to eliminate the line breaks / carriage returns of each line. To do this, str.strip()
is used:
data = open('datos.txt')
print('Imprimiendo última letra de cada línea:')
for cadenaaux in data:
cadenaaux = cadenaaux.strip()
print(cadenaaux[-1])
data.close()
Exit:
Printing last letter of each line:
a
e
=========
As for your problem in particular, you can use if (cadenaaux.count('.') > 0 and cadenaaux[-1] != '.'):
but keep in mind that for example:
the red car.house.
would not meet the condition.
Another option would be to use regular expressions as well:
import re
if re.search(r'\w\.\w', cadenaaux):
If you want to get the substrings separated by the points you can use re.split()
or str.split()
:
cadenaaux = "el carro rojo.casa"
subcadenas= [s for s in cadenaaux.split('.') if s]
print(subcadenas)
Exit:
['the red car', 'home']