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 문자열의 요소 읽기

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