%% Use Python str Variables in MATLAB
% This example shows how to use Python® str variables in MATLAB®.
%% Call Python Function With str Input Arguments
% To call a Python function that takes a str input argument, pass a MATLAB string or a character vector. MATLAB automatically converts the values to the Python str type.
% For example, the Python os.listdir function gets information about the contents of a folder, specified as type str. Create a character vector representing a valid folder and call os.listdir. The number of example folders is based on your installed product.

folder = fullfile(matlabroot,'help','examples');
F = py.os.listdir(folder);
exFolders = py.len(F)

%
%% Use Python str Type in MATLAB
% In MATLAB, a Python string is a py.str variable. To use this variable in MATLAB, call char. For example, the Python os.path.pathsep function returns the Python path separator character, a semicolon (;).

p = py.os.path.pathsep

% To insert this character between path names, type:

['mypath' char(p) 'nextpath']

%
%% Read Elements in Python String
% You can index into a Python string the same way you index into a MATLAB string. Create a MATLAB character vector and display a range of characters.

str = 'myfile';
str(2:end)

% Convert the character vector to a Python str type and display the same characters.

pstr = py.str(str);
pstr(2:end)

%
%% Pass MATLAB Backslash Control Character
% To pass the backslash control character (\) as a Python str type, insert the new line control character \n by calling the MATLAB sprintf function. Python replaces \n with a new line.

py.str(sprintf('The rain\nin Spain.'))

% Without the sprintf function, both MATLAB and Python interpret \ as a literal backslash.

py.str('The rain\nin Spain.')

% Pass this string to the Python string method split. Python treats the MATLAB character vector as a raw string and adds a \ character to preserve the original backslash.

split(py.str('The rain\nin Spain.'))

%
% Copyright 2020 The MathWorks, Inc.