Main Content

MATLAB での Python str 変数の使用

この例では、MATLAB® で Python® の str 変数を使用する方法を説明します。

str 入力引数を指定した Python 関数の呼び出し

str 入力引数を取る Python 関数を呼び出すには、MATLAB string または文字ベクトルを渡します。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 文字列の要素の読み取り

Python 文字列へのインデックス付けは、MATLAB string へのインデックス付けと同じ方法で行うことができます。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 文字ベクトルを "raw 文字列" として扱い、元のバックスラッシュを保持するために \ 文字を追加します。

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

    ['The', 'rain\\nin', 'Spain.']