Adding and saving whitespace/space characters to words

Dear all,

Thanks for looking.

I need to add spaces or blanks to individual ‘source’ words.
Each word HAS to be a given length - 20 characters. The client system can only accept fixed length entries.

When a word is shorter or longer than required, the entry is rejected. I have been able to trim words that are too long.

So here is an example ;
“HEADROOM/SAN” is 12 characters long
what is needed is
"HEADROOM/SAN " which is 20 characters long.

Extensive Googling, reading the Apple manual and so on have not thrown up a guide, or at least I have been unable to find one.

Can anybody suggest where I might look?

Thanks for reading this.


This is a simple handler. It appends the character until the desired length is reached

on pad(theText, theCharacter, maxLength)
	repeat while length of theText < maxLength
		set theText to theText & theCharacter
	end repeat
	return theText
end pad

set testString to "HEADROOM/SAN"
set testString to pad(testString, space, 20) 


Perfect and really simple/compact.

I was unaware I could ‘declare/use’ space. I was trying to use %20 or " " and so on.
set testString to pad(testString, space, 20)

Thanks for your trouble.


Heres a version that doesn’t have a loop

on pad(theText)
	set c to length of theText
	if c ≥ 20 then return
	set c to 20 - c
	return theText & text 1 thru c of "                    " -- the string is made up of 20 spaces
end pad

set testString to "HEADROOM/SAN"
set testString to pad(testString)

It might be faster, but the spaces are hard-coded

**EDIT - removed the passed “maxLength” variable since I hard-coded it for length of 20

Hello Robert,

Thanks for your script too. I have used Stefan’s script because the loop allows me to add a couple of other operations within the same loop.

As always happens, you and Stefan have both taught me something new.

Thanks for sending it over.

Max (Headroom San)

Another very simple way is to concatenate the text string with a sequence of spaces, before or after, and then take the left or right desired number of characters. For example:

set targetLength to 20
set thePad to "                      " -- 19 spaces 
set testString to "HEADROOM/SAN"
set finalTestString to (testString & thePad)

set finalResult to text 1 thru targetLength of finalTestString

--return finalResult --> "HEADROOM/SAN        "
--return the number of characters of finalResult --> 20

–Padding a number with leading zeroes
–Example: leading zeroes to pad to three places

set theLeadingPad to "000"
set testNum to "7"
set finalNumber to text from -3 to -1 of (theLeadingPad & testNum)

--return finalNumber --> "007"