数据类型-字符串

在MATLAB命令窗口使用py.str()可以创建Python字符串,然后可以使用Python中处理字符串的函数操作它们。

下面对给定的字符串用空格进行分割。

code.matlab
>> s=py.str('Hello MATLAB Python').split()
s =
	包含以下值的Python list:
	['Hello', 'MATLAB', 'Python']

下面将给定字符串的首字母大写,其他字母小写。

code.matlab
>> s=py.str('Hello MATLAB Python').capitalize()
s =
	Python str(不带属性)
	Hello matlab python

下面将给定字符串中的“Hello”替换为“Hi”。

code.matlab
>> s=py.str('Hello MATLAB Python').replace('Hello','Hi')
s =
	Python str(不带属性)
	Hi MATLAB Python

下面的例子演示如何用Python的os.listdir方法显示目录中的内容。创建一个名称合法的MATLAB变量。

code.matlab
>> folder=fullfile(matlabroot,'toolbox','dotnetbuilder')
folder =
	'D:\Program Files\MATLAB\R2023b\toolbox\dotnetbuilder'

将folder传给os.listdir函数。MATLAB自动将folder转换为Python的str类型。

code.matlab
>> py.os.listdir(folder)
ans =
包含以下值的 Python list:
['bin', 'dotnetbuilder', 'Examples']

MATLAB显示folder路径下的目录列表。

可以在MATLAB中使用Python的str类型。下面演示如何使用Python的路径分隔字符(;),在MATLAB中,Python字符是py.str变量。

code.matlab
>> p=py.os.path.pathsep
p=
Python str(不带属性)。
;

MATLAB使用相同的路径分隔符,即“;”。

code.matlab
>> c=pathsep
c=
;

比较MATLAB和Python的变量类型,py.str类型和MATLAB的char类型是不相同的。

code.matlab
>> isequal(class(p),class(c))
ans=
logical
0