Use Pythonstr
Variables in MATLAB
This example shows how to use Python®str
变量在MATLAB®。
Call Python Function Withstr
Input Arguments
To call a Python function that takes astr
input argument, pass a MATLAB string or a character vector. MATLAB automatically converts the values to the Pythonstr
type.
For example, the Pythonos.listdir
function gets information about the contents of a folder, specified as typestr
. Create a character vector representing a valid folder and callos.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] 267
Use Pythonstr
Type in MATLAB
In MATLAB, a Python string is apy.str
variable. To use this variable in MATLAB, callchar
. For example, the Pythonos.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 Pythonstr
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 Pythonstr
type, insert the new line control character\n
by calling the MATLABsprintf
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 thesprintf
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 methodsplit
. Python treats the MATLAB character vector as araw stringand adds a\
character to preserve the original backslash.
split(py.str('The rain\nin Spain.'))
ans = Python list with no properties. ['The', 'rain\\nin', 'Spain.']