matlab 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.']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值