Extract City from Address Returned by Google Maps

I have the following sensors which return the address among other attributes

# Travel time from Dist Location to Home
  - platform: google_travel_time
    name: Dist To Home
    api_key: abcdefghijklmnopqrstuvwxyz
    origin:  device_tracker.life360_mobile
    destination: zone.home

The above returns a string with the address in the attribute origin_addresses.
Now I am using the following sensor to extract the address, but I would like to extract only the Town/City, which is the string between commas, e.g. [‘8 Big Street, Valletta, Malta’] .
Is there a way to extract only the string Valletta instead of the whole string?

# Mobile Current Location
  - platform: template
    sensors:
      mobile_current_location:
        value_template: '{{ states.sensor.dist_to_home.attributes.origin_addresses|default(0) }}'
        friendly_name: Mobile Current Location
        icon_template: mdi:crosshairs-gps

thanks in advance

If the attribute always exists, and is always in the format you describe, then the following should do it:

value_template: >
  {{ state_attr('sensor.dist_to_home', 'origin_addresses').split(',')[1].strip() }}

If the attribute doesn’t always exist, or it isn’t always in that exact format, let me know and I can adjust the template to account for those situations as well.

See this Google Geocode Custom Component - GPS to Street Address

thanks Phil, till now field is always available and format is constant.
I tried your suggestion under Developer Tools > Template but I am getting an error “Error rendering template: UndefinedError: ‘list object’ has no attribute ‘split’”

Interesting. What does this look like in the Template Editor:

{{ state_attr('sensor.dist_to_home', 'origin_addresses') }}

EDIT: Oh, I just noticed. Try this instead:

value_template: >
  {{ state_attr('sensor.dist_to_home', 'origin_addresses')[0].split(',')[1].strip() }}
1 Like

thanks Phil … worked perfectly. Full sensor config below for reference:

     - platform: template
     sensors:
       mobile_current_location:
         value_template: "{{ state_attr('sensor.dist_to_home', 'origin_addresses')[0].split(',')[1].strip() }}"
         friendly_name: Mobile Current Location
        icon_template: mdi:crosshairs-gps