在 MATLAB 中使用 Python str
变量
此示例说明如何在 MATLAB® 中使用 Python® str
变量。
用 str
输入参数调用 Python 函数
要调用接受 str
输入参数的 Python 函数,请传递 MATLAB 字符串或字符向量。MATLAB 自动将这些值转换为 Python str
类型。
例如,Python os.listdir
函数获取有关文件夹内容的信息,指定为类型 str
。创建一个表示有效文件夹的字符向量并调用 os.listdir
。示例文件夹的数量基于您安装的产品。
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
在 MATLAB 中使用 Python str
类型
在 MATLAB 中,Python 字符串是 py.str
变量。要在 MATLAB 中使用此变量,请调用 char
。例如,Python os.path.pathsep
函数返回 Python 路径分隔符,即分号 (;
)。
p = py.os.path.pathsep
p = Python str with no properties. ;
要在路径名称之间插入此字符,请键入:
['mypath' char(p) 'nextpath']
ans = 'mypath;nextpath'
读取 Python 字符串中的元素
您可以像对 MATLAB 字符串进行索引一样对 Python 字符串进行索引。创建一个 MATLAB 字符向量并显示某字符范围。
str = 'myfile';
str(2:end)
ans = 'yfile'
将该字符向量转换为 Python str
类型并显示相同的字符。
pstr = py.str(str); pstr(2:end)
ans = Python str with no properties. yfile
传递 MATLAB 反斜杠控制字符
要将反斜杠控制字符 (\
) 作为 Python str
类型传递,请通过调用 MATLAB sprintf
函数插入新行控制字符 \n
。Python 会用一个新行替换 \n
。
py.str(sprintf('The rain\nin Spain.'))
ans = Python str with no properties. The rain in Spain.
如果没有 sprintf
函数,MATLAB 和 Python 都会将 \
解释为字面值反斜杠。
py.str('The rain\nin Spain.')
ans = Python str with no properties. The rain\nin Spain.
将此字符串传递给 Python 字符串方法 split
。Python 将 MATLAB 字符向量视为原始字符串,并添加 \
字符来保留原始反斜杠。
split(py.str('The rain\nin Spain.'))
ans = Python list with no properties. ['The', 'rain\\nin', 'Spain.']