String formatting in Xojo

Hello everyone. I’m “playing” with Xojo and sometimes I’m struggling to find a way to do the things I do easily with other languages, in my case… “python”!

How I do the string formatting in Xojo?

name = "John"
surname = "Doe"
age = 30
output = "I'am %s %s and I have %s years" % (name, surname, age)

Thank you

[code]
Dim name As String = “John”
Dim surname As String = “Doe”
Dim age As Integer = 30

output = “I am " + name + " " + surname + " and I have " + Str(age) + " years”[/code]

Or, if you prefer the Python style, create a module with a method (untested, may be prone to typos)

Function PyReplace(extends s as string, Paramarray terms as String) As String For q as Integer = 0 to terms.ubound s = s.Replace("%s", terms(q)) next Return s End Function
and call it with

output = "I'am %s %s and I have %s years".PyReplace (name, surname, age)

Age should be a string too. If not, you could extend the method to receive variants and try to cast their stringValue.

These are intended to be implemented in a Module.

Function Substitute(extends source as string, subs() as string) As String
//--------------------------------------------------------------------------------------------------------------------------------
// Purpose : Substitute ‘{#}’ in source for the indexed element in sub()
// Parameters: source - The source string
// sub() - Strings to be substituted
// Returns : Modified string
// Notes : -
//--------------------------------------------------------------------------------------------------------------------------------

	  dim modString as string = source
	  
	  for i as int32= 0 to subs.Ubound
	    modString = modString.ReplaceAll("{"+str(i)+"}", subs(i))
	  next i
	  
	  return modString

End Function

Function Substitute(extends source as string, paramarray subs as string) As String
//--------------------------------------------------------------------------------------------------------------------------------
// Purpose : Substitute ‘{#}’ in source for the indexed element in sub()
// Parameters: source - The source string
// subs - Strings to be substituted
// Returns : Modified string
// Notes : -
//--------------------------------------------------------------------------------------------------------------------------------

	  dim mySubs() as string = subs  //Convert the paramarray into an array
	  
	  return source.Substitute(mySubs)

End Function

See the StringUtils library here: http://www.strout.net/info/coding/rb/intro.html

Coming from Python you will probably appreciate the Slice methods included in ArrayUtils :slight_smile:

Thank you, Ulrich! ParamArray is fantastic!: ParamArray — Xojo documentation

I can’t believe I haven’t learned about that before.