Asdfg Asdfg - 1 month ago 5
Python Question

Python - read everything after second or third last dot

I need to get the below output from the input.

Input1: firstname.middlename.lastname.city.state
Expected output: city.state

Input2: firstname.middlename.lastname.city.state.
Expected output: city.state


This is the expression i have that works when the Input does not have . at the end:

'firstname.middlename.lastname.city.state'['firstname.middlename.lastname.city.state'[:'firstname.middlename.lastname.city.state'.rfind(".")].rfind(".")+1:]


How do i modify this expression so that
Input2
has the same output as
Input1

Answer
input_ = 'firstname.middlename.lastname.city.state.'
x = [a for a in input_.split('.') if a]

print('.'.join(x[-2:])) # prints city.state

Works with both input.

Comments