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)
exFolders =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
3
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
p =
Python str with no properties.
;
To insert this character between path names, type:
['mypath' char(p) 'nextpath']
ans = 'mypath;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)ans = 'yfile'
Convert the character vector to a Python str type and display the same characters.
pstr = py.str(str); pstr(2:end)
ans =
Python str with no properties.
yfile
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.'))ans =
Python str with no properties.
The rain
in Spain.
Without the sprintf function, both MATLAB and Python interpret \ as a literal backslash.
py.str('The rain\nin Spain.')ans =
Python str with no properties.
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.'))ans =
Python list with values:
['The', 'rain\\nin', 'Spain.']
Use string, double or cell function to convert to a MATLAB array.