Skip to main content

String Manipulation

This document gives an overview of some of the string manipulation functions and how to use them. See API Reference for all the available functions and their detail.

Format a string (variable substitution)#

print(format('My name is %s. I am %s', 'Joe', 23))# prints, My name is Joe. I am 23

Convert a string to title case#

print(title('we are going to get some food')) # prints, We Are Going To Get Some Food

Trim a string from start#

print(trimStart("Don't go there", "Don't ")) # prints, go there

Get Substring from a string using indexes#

foo = 'This is going to be good start'print(substring(foo, indexOf(foo, 'good'))) # prints, good start

Get substring from a string using regex#

From other ways, the easiest is to provide a pattern with no capture groups. All subsequences in a string that matches the given pattern are returned as a list. For example:

text = 'I got this phone from a mall for $1000, think I saved at least $500'regex = '\\$[1-9][0-9]{1,3}'# result will be a list containing the matchesresult = substringRegex(text, regex)print(result) # prints [$1000, $500]

Replace all occurrences of a substring with another string matched by a pattern#

The following example makes use of capture groups to keep the matched values and build a replacement string using them.

text = 'Save your $$$. Now get $50 discount on every $500 spent.'# Replace all occurrences of '$xx' to 'USDxx'pattern = '\\$(?<price>[1-9][0-9]{0,4})'replacement = 'USD${price}'print(replaceAll(text, pattern, replacement))# prints, Save your $$$. Now get USD50 discount on every USD500 spent.# Note that we can't just replace '$' with 'USD' as the text#  contains '$' symbols that are not associated with a price.

Joining a list of strings#

texts = ['I found', 'you', 'hanging out there']print(join(' ', texts))# prints, I found you hanging out there