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')

  mydata.csv

% remove file ending '.txt'

filename = 'mydata.txt'

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

  mydata

% alternatively, use: 'erase'

rawname = erase(filename,'.txt')

  mydata

% using startswith and endswith to check presence of substring

filename = 'mydata.txt'

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

  mydata

Check / find substring

check for substring 'day'

~isempty(strfind('Friday','day'))

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

get position of substring

strfind('Friday','day')

 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}

  'subjectA'

s2 = ID{2}

  'sample02'



Read more

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