Main Content

Use PythonstrVariables in MATLAB

This example shows how to use Python®strvariables in MATLAB®.

Call Python Function WithstrInput Arguments

To call a Python function that takes astrinput argument, pass a MATLAB string or a character vector. MATLAB automatically converts the values to the Pythonstrtype.

For example, the Pythonos.listdirfunction 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 PythonstrType in MATLAB

In MATLAB, a Python string is apy.strvariable. To use this variable in MATLAB, callchar. For example, the Pythonos.path.pathsepfunction 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 Pythonstrtype 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 Pythonstrtype, insert the new line control character\nby calling the MATLABsprintffunction. Python replaces\nwith a new line.

py.str(sprintf('The rain\nin Spain.'))
ans = Python str with no properties. The rain in Spain.

Without thesprintffunction, 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.

将此字符串传递给Python字符串方法split. 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.']