President Barack Obama has told law enforcement officials that Americans recognize, respect and depend upon the difficult and dangerous work they do, a rallying call of support following the ambush killings of eight officers in Dallas and Baton Rouge.

Three police officers were gunned down in Louisiana's state capital on Sunday by a U.S. Marine Corps veteran with ties to an African-American anti-government group, authorities said. On July 7, another former U.S. serviceman espousing militant black nationalist views killed five Dallas officers.

"Just as your tight-knit law enforcement family feels the recent losses to your core, our nation grieves alongside you," Obama said in an open letter dated July 18 that was published by the White House on Tuesday.

"Thank you for your courageous service. We have your backs," the president wrote.

Authorities identified the Baton Rouge gunman as former Sergeant Gavin Long of Kansas City, Missouri, an Iraq war veteran, and said he seemed determined to slay as many police officers as possible before a SWAT team marksman cut short his attack.

The single gunshot that killed Long, 29, was fired by an officer from about 100 yards away, police have said as they deepened their investigation into the second racially charged armed assault on U.S. law enforcement this month.

The Dallas shooting happened at the end of an otherwise peaceful protest denouncing the fatal police shootings of two black men days earlier, one of them in Baton Rouge.

Obama said nothing could be more patriotic and professional than police officers protecting demonstrators who were protesting against them, and he said that was a proud example of the country's most basic freedoms.

"This is a time to reaffirm that what makes us special is that we are not only a country, but also a community," he wrote. "That is true whether you are black or white, whether you are rich or poor, whether you are a police officer or someone they protect and serve."

Police have declined to say what role race might have played in Sunday's rampage, which killed two white officers and one black officer. Three more officers were wounded, one of them critically.