Here is a toy program that may illustrate how to do this. It uses the non-standard function "len_trim", which is provided by many compilers.
program varfmt
character myFmt*10,myStr*20
myStr='This is my string'
write(myFmt,10)len_Trim(myStr)
10 format('(1x,A',I2,')')
write(*,myFmt)myStr
stop
end