like knowing what comes after a specific character in a string in python

0

for example I have this chain the Red car. and I want to know if after that. another word comes I had thought of this solution

cadenaaux = "el carro rojo.casa"
if (cadenaaux.count('.') > 0 and cadenaaux[-1] != '.'):

but the last position of that string gives me empty and I do not know why I should return the last character that would be 'a' but not then I do not know if there would be an established function that would help me

    
asked by Efrainrodc 07.05.2017 в 04:52
source

1 answer

1

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']

    
answered by 07.05.2017 / 06:03
source