Strings

Python | Matlab

Replace substring

# replace all characters "a" with "x"

gsub("a", "x", "a1 a2 a3 a4")

"x1 x2 x3 x4"

# replace file ending ".txt" with ".csv"

filename = "mydata.txt"

newFilename = gsub(".txt", ".csv", filename)

mydata.csv

# remove file ending ".txt"

filename = "mydata.txt"

rawname = gsub(".txt", "", filename)

mydata

Split and merge text strings

# split a string using the comma

strsplit('A,B,C',',')

"A" "B" "C"

# join / concatenate a list to a string

paste('A', 'B', 'C')

"A B C"

paste('A', 'B', 'C', sep='-')

"A-B-C"

paste('A', 'B', 'C', sep='')

"ABC"

# formatted output string

sprintf('Results of %s is %.2f', 'A' , 2.47361)

"Results of A is 2.47"