Python | R

Replace substring

% replace all characters "a" with "x"

strrep('a1 a2 a3 a4', 'a', 'x')

   'x1 x2 x3 x4'

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

filename    = 'mydata.txt'

newFilename = strrep(filename, '.txt', '.csv')


% remove file ending '.txt'

filename = 'mydata.txt'

rawname  = strrep(filename, '.txt', '')


% alternatively, use: 'erase'

rawname = erase(filename,'.txt')


% using startswith and endswith to check presence of substring

filename = 'mydata.txt'

if endsWith(filename,'.txt'), filename = erase(filename,'.txt'), end


Check / find substring

check for substring 'day'


 1  % True: substring 'day' appears in string 'Friday'

get position of substring


 4  % substring 'day' starts at character position 4 in string 'Friday'

Split a string

# separate words using the delimiter '_'

ID = strsplit('subjectA_sample02','_')

  {'subjectA'}    {'sample02'}

Result of strsplit is a cell array 

s1 = ID{1}


s2 = ID{2}


Read more

→ Cell arrays: edit text in cell fields     replace, find, remove, ...