Unicode オブジェクトと codec

Unicode オブジェクト

Python3.3 の PEP 393 実装から、メモリ効率を維持しながらUnicode文字の完全な範囲を扱えるように、Unicodeオブジェクトは内部的に多様な表現形式を用いています。すべてのコードポイントが128、256または65536以下の文字列に対して特別なケースが存在しますが、それ以外ではコードポイントは1114112以下(これはすべてのUnicode範囲です)でなければなりません。

UTF-8 representation is created on demand and cached in the Unicode object.

注釈

The Py_UNICODE representation has been removed since Python 3.12 with deprecated APIs. See PEP 623 for more information.

Unicode 型

以下は Python の Unicode 実装に用いられている基本 Unicode オブジェクト型です:

type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI.

これらの型は、それぞれ、32ビット、16ビット、そして8ビットの文字を保持するのに充分な幅を持つ符号なしの整数型のtypedefです。単一のUnicode文字を扱う場合は、 Py_UCS4 を用いてください。

バージョン 3.3 で追加.

type Py_UNICODE

これは、wchar_t のtypedef で、プラットフォームに依存して16ビットか32ビットの型になります。

バージョン 3.3 で変更: 以前のバージョンでは、Pythonをビルドした際に "narrow" または "wide" Unicode バージョンのどちらを選択したかによって、 16ビットか32ビットのどちらかの型になっていました。

type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject

これらの PyObject のサブタイプは Python Unicode オブジェクトを表現します。 Unicode オブジェクトを扱う全ての API 関数は PyObject へのポインタを受け取って PyObject へのポインタを返すので、ほとんどの場合、これらの型を直接使うべきではありません。

バージョン 3.3 で追加.

PyTypeObject PyUnicode_Type
Part of the Stable ABI.

この PyTypeObject のインスタンスは、Python Unicode型を表します。これは、Pythonコードに str として露出されます。

The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of Unicode objects:

int PyUnicode_Check(PyObject *obj)

オブジェクト obj が Unicode オブジェクトか Unicode 型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。

int PyUnicode_CheckExact(PyObject *obj)

オブジェクト obj が Unicode オブジェクトだがサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。

int PyUnicode_READY(PyObject *unicode)

Returns 0. This API is kept only for backward compatibility.

バージョン 3.3 で追加.

バージョン 3.10 で非推奨: This API does nothing since Python 3.12.

Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)

Unicode 文字列のコードポイントでの長さを返します。 unicode は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で追加.

Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)

文字に直接アクセスするために、 UCS1, UCS2, UCS4 のいずれかの整数型にキャストされた正統な表現形式へのポインタを返します。 正統な表現が適正な文字サイズになっているかどうかのチェックはしません; PyUnicode_KIND() を使って正しい関数を選んでください。

バージョン 3.3 で追加.

PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND

PyUnicode_KIND() マクロの返り値です。

バージョン 3.3 で追加.

バージョン 3.12 で変更: PyUnicode_WCHAR_KIND は削除されました。

int PyUnicode_KIND(PyObject *unicode)

この Unicode がデータを保存するのに1文字あたり何バイト使っているかを示す PyUnicode 種別の定数 (上を読んでください) のうち1つを返します。 unicode は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で追加.

void *PyUnicode_DATA(PyObject *unicode)

生の Unicode バッファへの void ポインタを返します。 unicode は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で追加.

void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)

正統な表現形式となっている (PyUnicode_DATA() で取得した) data に書き込みます。 この関数は正常性のチェックを行わない、ループで使われるためのものです。 呼び出し側は、他の呼び出しで取得した kind 値と data ポインタをキャッシュすべきです。 index は文字列の (0始まりの) インデックスで、 value はその場所に書き込まれることになる新しいコードポイントの値です。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)

正統な表現形式となっている (PyUnicode_DATA() で取得した) data からコードポイントを読み取ります。 チェックや事前確認のマクロ呼び出しは一切行われません。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)

Unicode オブジェクト unicode から文字を読み取ります。 この Unicode オブジェクトは "正統な" 表現形式でなければなりません。 何度も連続して読み取る場合には、このマクロは PyUnicode_READ() よりも非効率的です。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)

unicode に基づいて他の文字列を作るのに適した最大のコードポイントを返します。 この Unicode オブジェクトは "正統な" 表現形式でなければなりません。 この値は常に概算値ですが、文字列全体を調べるよりも効率的です。

バージョン 3.3 で追加.

int PyUnicode_IsIdentifier(PyObject *unicode)
Part of the Stable ABI.

文字列が、 識別子 (identifier) およびキーワード (keyword) 節の言語定義における有効な識別子であれば 1 を返します。それ以外の場合は 0 を返します。

バージョン 3.9 で変更: The function does not call Py_FatalError() anymore if the string is not ready.

Unicode 文字プロパティ

Unicode は数多くの異なる文字プロパティ (character property) を提供しています。よく使われる文字プロパティは、以下のマクロで利用できます。これらのマクロは Python の設定に応じて、各々 C の関数に対応付けられています。

int Py_UNICODE_ISSPACE(Py_UCS4 ch)

ch が空白文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISLOWER(Py_UCS4 ch)

ch が小文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISUPPER(Py_UCS4 ch)

ch が大文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISTITLE(Py_UCS4 ch)

ch がタイトルケース文字 (titlecase character) かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)

ch が改行文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)

ch が decimal 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISDIGIT(Py_UCS4 ch)

ch が digit 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)

ch が数字 (numeric) 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISALPHA(Py_UCS4 ch)

ch がアルファベット文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISALNUM(Py_UCS4 ch)

ch が英数文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)

ch が文字が印字可能な文字かどうかに基づいて 1 または 0 を返します。 非印字可能文字は、 Unicode 文字データベースで "Other" または "Separator" と定義されている文字の、印字可能と見なされる ASCII space (0x20) 以外のものです。 (なお、この文脈での印字可能文字は、文字列に repr() が呼び出されるときにエスケープすべきでない文字のことです。これは sys.stdoutsys.stderr に書き込まれる文字列の操作とは関係ありません。)

以下の API は、高速に直接文字変換を行うために使われます:

Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)

ch を小文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)

ch を大文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)

ch をタイトルケース文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

int Py_UNICODE_TODECIMAL(Py_UCS4 ch)

Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This function does not raise exceptions.

int Py_UNICODE_TODIGIT(Py_UCS4 ch)

Return the character ch converted to a single digit integer. Return -1 if this is not possible. This function does not raise exceptions.

double Py_UNICODE_TONUMERIC(Py_UCS4 ch)

ch を double に変換したものを返します。不可能ならば -1.0 を返します。この関数は例外を送出しません。

これらの API はサロゲートにも使えます:

int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)

ch がサロゲートかどうか (0xD800 <= ch <= 0xDFFF) をチェックします。

int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)

ch が上位サロゲートかどうか (0xD800 <= ch <= 0xDBFF) をチェックします。

int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)

ch が下位サロゲートかどうか (0xDC00 <= ch <= 0xDFFF) をチェックします。

Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)

Join two surrogate characters and return a single Py_UCS4 value. high and low are respectively the leading and trailing surrogates in a surrogate pair. high must be in the range [0xD800; 0xDBFF] and low must be in the range [0xDC00; 0xDFFF].

Unicode 文字列の生成とアクセス

Unicode オブジェクトを生成したり、Unicode のシーケンスとしての基本的なプロパティにアクセスしたりするには、以下の API を使ってください:

PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference.

新しい Unicode オブジェクトを生成します。 maxchar は文字列に並べるコードポイントの正しい最大値にすべきです。 その値は概算値として 127, 255, 65535, 1114111 の一番近い値に切り上げられます。

これは新しい Unicode オブジェクトを生成する推奨された方法です。 この関数を使って生成されたオブジェクトはサイズ変更は不可能です。

バージョン 3.3 で追加.

PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference.

与えられた kind (取り得る値は PyUnicode_1BYTE_KIND などの PyUnicode_KIND() が返す値です) の Unicode オブジェクトを生成します。 buffer は、与えられた kind に従って1文字あたり 1, 2, 4 バイトのいずれかを単位として、長さ size の配列へのポインタでなければなりません。

If necessary, the input buffer is copied and transformed into the canonical representation. For example, if the buffer is a UCS4 string (PyUnicode_4BYTE_KIND) and it consists only of codepoints in the UCS1 range, it will be transformed into UCS1 (PyUnicode_1BYTE_KIND).

バージョン 3.3 で追加.

PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object from the char buffer str. The bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might be a shared object, i.e. modification of the data is not allowed.

This function raises SystemError when:

  • size < 0,

  • str is NULL and size > 0

バージョン 3.12 で変更: str == NULL with size > 0 is not allowed anymore.

PyObject *PyUnicode_FromString(const char *str)
Return value: New reference. Part of the Stable ABI.

UTF-8 エンコードされたnull終端のchar 型バッファ str から Unicode オブジェクトを生成します。

PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI.

Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the format ASCII-encoded string.

一つの変換指定子は 2 またはそれ以上の文字を含み、その構成要素は以下からなりますが、示した順に出現しなければなりません:

  1. 指定子の開始を示す文字 '%'

  2. 変換フラグ (オプション)。一部の変換型の結果に影響します。

  3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next argument, which must be of type int, and the object to convert comes after the minimum field width and optional precision.

  4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is given in the next argument, which must be of type int, and the value to convert comes after the precision.

  5. 精度長変換子 (オプション)。

  6. 変換型。

変換フラグ文字を以下に示します:

Flag

意味

0

数値型に対してゼロによるパディングを行います。

-

The converted value is left adjusted (overrides the 0 flag if both are given).

The length modifiers for following integer conversions (d, i, o, u, x, or X) specify the type of the argument (int by default):

修飾子

l

long または unsigned long

ll

long long または unsigned long long

j

intmax_t or uintmax_t

z

size_t or ssize_t

t

ptrdiff_t

The length modifier l for following conversions s or V specify that the type of the argument is const wchar_t*.

The conversion specifiers are:

Conversion Specifier

備考

%

n/a

The literal % character.

d, i

Specified by the length modifier

The decimal representation of a signed C integer.

u

Specified by the length modifier

The decimal representation of an unsigned C integer.

o

Specified by the length modifier

The octal representation of an unsigned C integer.

x

Specified by the length modifier

The hexadecimal representation of an unsigned C integer (lowercase).

X

Specified by the length modifier

The hexadecimal representation of an unsigned C integer (uppercase).

c

int

A single character.

s

const char* または const wchar_t*

null で終端された C の文字列。

p

const void*

C ポインタの 16 進表記。printf("%p") とほとんど同じですが、プラットフォームにおける printf の定義に関わりなく先頭にリテラル 0x が付きます。

A

PyObject*

ascii() の戻り値。

U

PyObject*

Unicode オブジェクト。

V

PyObject*, const char* or const wchar_t*

A Unicode object (which may be NULL) and a null-terminated C character array as a second parameter (which will be used, if the first parameter is NULL).

S

PyObject*

PyObject_Str() の戻り値。

R

PyObject*

PyObject_Repr() の戻り値。

注釈

The width formatter unit is number of characters rather than bytes. The precision formatter unit is number of bytes or wchar_t items (if the length modifier l is used) for "%s" and "%V" (if the PyObject* argument is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject* argument is not NULL).

注釈

Unlike to C printf() the 0 flag has effect even when a precision is given for integer conversions (d, i, u, o, x, or X).

バージョン 3.2 で変更: "%lld", "%llu" のサポートが追加されました。

バージョン 3.3 で変更: "%li", "%lli", "%zi" のサポートが追加されました。

バージョン 3.4 で変更: "%s", "%A", "%U", "%V", "%S", "%R" での幅フォーマッタおよび精度フォーマッタのサポートが追加されました。

バージョン 3.12 で変更: Support for conversion specifiers o and X. Support for length modifiers j and t. Length modifiers are now applied to all integer conversions. Length modifier l is now applied to conversion specifiers s and V. Support for variable width and precision *. Support for flag -.

An unrecognized format character now sets a SystemError. In previous versions it caused all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded.

PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI.

ちょうど2つの引数を取ることを除いて、 PyUnicode_FromFormat() と同じです。

PyObject *PyUnicode_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI.

Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return a new strong reference to the object.

Unicode やそのサブタイプ以外のオブジェクトでは TypeError が引き起こされます。

PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI.

エンコードされている obj を Unicode オブジェクトにデコードします。

bytesbytearray や他の bytes-like objects は、与えられた encoding に従ってデコードされ、 errors で定義されたエラーハンドリングが使われます。 これらの引数は両方とも NULL にでき、その場合この API はデフォルト値を使います (詳しことは 組み込み codec (built-in codec) を参照してください)。

その他のUnicodeオブジェクトを含むオブジェクトは TypeError 例外を引き起こします。

この API は、エラーが生じたときには NULL を返します。呼び出し側は返されたオブジェクトに対し参照カウンタを 1 つ減らす (decref) する責任があります。

Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Part of the Stable ABI since version 3.7.

Unicode オブジェクトの長さをコードポイントで返します。

バージョン 3.3 で追加.

Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)

ある Unicode オブジェクトから他へ文字をコピーします。 この関数は必要なときに文字変換を行い、可能な場合は memcpy() へ差し戻します。 失敗のときには -1 を返し、例外を設定します。そうでない場合は、コピーした文字数を返します。

バージョン 3.3 で追加.

Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

文字列を文字で埋めます: unicode[start:start+length]fill_char を埋めることになります。

fill_char が文字列の最大文字よりも大きい場合や、文字列2つ以上の参照を持ってた場合は失敗します。

書き込んだ文字数を返すか、失敗のときには -1 を返し例外を送出します。

バージョン 3.3 で追加.

int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
Part of the Stable ABI since version 3.7.

文字列に文字を書き込みます。 文字列は PyUnicode_New() で作成しなければなりません。 Unicode 文字列は不変とされているので、この文字列は共有されていたり、これまでにハッシュ化されていてはいけません。

この関数は unicode が Unicode オブジェクトであること、インデックスが範囲内であること、オブジェクトが安全に変更できる (つまり参照カウントが1である) ことをチェックします。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Part of the Stable ABI since version 3.7.

文字列から文字を読み取ります。 エラーチェックを行わない PyUnicode_READ_CHAR() とは対照的に、この関数は unicode が Unicode オブジェクトであること、インデックスが範囲内であることをチェックします。

バージョン 3.3 で追加.

PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
Return value: New reference. Part of the Stable ABI since version 3.7.

Return a substring of unicode, from character index start (included) to character index end (excluded). Negative indices are not supported.

バージョン 3.3 で追加.

Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Part of the Stable ABI since version 3.7.

Copy the string unicode into a UCS4 buffer, including a null character, if copy_null is set. Returns NULL and sets an exception on error (in particular, a SystemError if buflen is smaller than the length of unicode). buffer is returned on success.

バージョン 3.3 で追加.

Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *unicode)
Part of the Stable ABI since version 3.7.

文字列 unicodePyMem_Malloc() でメモリ確保された新しい UCS4 型のバッファにコピーします。 これが失敗した場合は、 NULL を返し MemoryError をセットします。 返されたバッファは必ず null コードポイントが追加されています。

バージョン 3.3 で追加.

ロケールエンコーディング

現在のロケールエンコーディングはオペレーティングシステムのテキストをデコードするのに使えます。

PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

Decode a string from UTF-8 on Android and VxWorks, or from the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383). The decoder uses "strict" error handler if errors is NULL. str must end with a null character but cannot contain embedded null characters.

Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and error handler.

This function ignores the Python UTF-8 Mode.

参考

Py_DecodeLocale() 関数。

バージョン 3.3 で追加.

バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを surrogateescape エラーハンドラで使うようになりました。 以前は、 Py_DecodeLocale()surrogateescape で使われ、現在のロケールエンコーディングは strict で使われていました。

PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().

バージョン 3.3 で追加.

PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383). The encoder uses "strict" error handler if errors is NULL. Return a bytes object. unicode cannot contain embedded null characters.

Use PyUnicode_EncodeFSDefault() to encode a string to the filesystem encoding and error handler.

This function ignores the Python UTF-8 Mode.

参考

Py_EncodeLocale() 関数。

バージョン 3.3 で追加.

バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを surrogateescape エラーハンドラで使うようになりました。 以前は、 Py_EncodeLocale()surrogateescape で使われ、現在のロケールエンコーディングは strict で使われていました。

ファイルシステムエンコーディング

Functions encoding to and decoding from the filesystem encoding and error handler (PEP 383 and PEP 529).

To encode file names to bytes during argument parsing, the "O&" converter should be used, passing PyUnicode_FSConverter() as the conversion function:

int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI.

ParseTuple converter: encode str objects -- obtained directly or through the os.PathLike interface -- to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is. result must be a PyBytesObject* which must be released when it is no longer used.

バージョン 3.1 で追加.

バージョン 3.6 で変更: path-like object を受け入れるようになりました。

引数の構文解析中にファイル名を str にデコードするには、 "O&" コンバーターを使い、 PyUnicode_FSDecoder() を変換関数として渡すのがよいです:

int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI.

ParseTuple converter: decode bytes objects -- obtained either directly or indirectly through the os.PathLike interface -- to str using PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no longer used.

バージョン 3.2 で追加.

バージョン 3.6 で変更: path-like object を受け入れるようになりました。

PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI.

Decode a string from the filesystem encoding and error handler.

If you need to decode a string from the current locale encoding, use PyUnicode_DecodeLocaleAndSize().

参考

Py_DecodeLocale() 関数。

バージョン 3.6 で変更: The filesystem error handler is now used.

PyObject *PyUnicode_DecodeFSDefault(const char *str)
Return value: New reference. Part of the Stable ABI.

Decode a null-terminated string from the filesystem encoding and error handler.

If the string length is known, use PyUnicode_DecodeFSDefaultAndSize().

バージョン 3.6 で変更: The filesystem error handler is now used.

PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Encode a Unicode object to the filesystem encoding and error handler, and return bytes. Note that the resulting bytes object can contain null bytes.

If you need to encode a string to the current locale encoding, use PyUnicode_EncodeLocale().

参考

Py_EncodeLocale() 関数。

バージョン 3.2 で追加.

バージョン 3.6 で変更: The filesystem error handler is now used.

wchar_t サポート

wchar_t をサポートするプラットフォームでの wchar_t サポート:

PyObject *PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object from the wchar_t buffer wstr of the given size. Passing -1 as the size indicates that the function must itself compute the length, using wcslen(). Return NULL on failure.

Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
Part of the Stable ABI.

Copy the Unicode object contents into the wchar_t buffer wstr. At most size wchar_t characters are copied (excluding a possibly trailing null termination character). Return the number of wchar_t characters copied or -1 in case of an error.

When wstr is NULL, instead return the size that would be required to store all of unicode including a terminating null.

Note that the resulting wchar_t* string may or may not be null-terminated. It is the responsibility of the caller to make sure that the wchar_t* string is null-terminated in case this is required by the application. Also, note that the wchar_t* string might contain null characters, which would cause the string to be truncated when used with most C functions.

wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.7.

Convert the Unicode object to a wide character string. The output string always ends with a null character. If size is not NULL, write the number of wide characters (excluding the trailing null termination character) into *size. Note that the resulting wchar_t string might contain null characters, which would cause the string to be truncated when used with most C functions. If size is NULL and the wchar_t* string contains null characters a ValueError is raised.

Returns a buffer allocated by PyMem_New (use PyMem_Free() to free it) on success. On error, returns NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.

バージョン 3.2 で追加.

バージョン 3.7 で変更: Raises a ValueError if size is NULL and the wchar_t* string contains null characters.

組み込み codec (built-in codec)

Python には、処理速度を高めるために C で書かれた codec が揃えてあります。これら全ての codec は以下の関数を介して直接利用できます。

以下の API の多くが、 encodingerrors という二つの引数をとります。これらのパラメータは、組み込みの文字列コンストラクタである str() における同名のパラメータと同じ意味を持ちます。

Setting encoding to NULL causes the default encoding to be used which is UTF-8. The file system calls should use PyUnicode_FSConverter() for encoding file names. This uses the filesystem encoding and error handler internally.

errors で指定するエラー処理もまた、 NULL を指定できます。 NULL を指定すると、codec で定義されているデフォルト処理の使用を意味します。全ての組み込み codec で、デフォルトのエラー処理は "strict" (ValueError を送出する) になっています。

個々の codec は全て同様のインターフェースを使っています。個別の codec の説明では、説明を簡単にするために以下の汎用のインターフェースとの違いだけを説明しています。

汎用 codec

以下は汎用 codec の API です:

PyObject *PyUnicode_Decode(const char *str, Py_ssize_t size, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object by decoding size bytes of the encoded string str. encoding and errors have the same meaning as the parameters of the same name in the str() built-in function. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI.

Unicode オブジェクトをエンコードし、その結果を Python の bytes オブジェクトとして返します。 encoding および errors は Unicode 型の encode() メソッドに与える同名のパラメータと同じ意味を持ちます。 使用する codec の検索は、 Python の codec レジストリを使って行います。 codec が例外を送出した場合には NULL を返します。

UTF-8 Codecs

以下は UTF-8 codec の APIです:

PyObject *PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

UTF-8 でエンコードされた size バイトの文字列 str から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL の場合、 PyUnicode_DecodeUTF8() と同じように動作します。 consumedNULL でない場合、末尾の不完全な UTF-8 バイト列はエラーとみなされません。これらのバイト列はデコードされず、デコードされたバイト数は consumed に格納されます。

PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

UTF-8 で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.10.

Unicode オブジェクトを UTF-8 でエンコードしたものへのポインタを返し、エンコードされた表現形式でのサイズ (バイト単位) を size に格納します。 size 引数は NULL でも構いません; その場合はサイズは格納されません。 返されるバッファには、 null コードポイントがあるかどうかに関わらず、常に null バイトが終端に付加されています (これは size には勘定されません)。

エラーが起きた場合は、 NULL を返し、例外を設定し、 size には何も格納しません。

This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected.

バージョン 3.3 で追加.

バージョン 3.7 で変更: 返り値の型が char * ではなく const char * になりました。

バージョン 3.10 で変更: This function is a part of the limited API.

const char *PyUnicode_AsUTF8(PyObject *unicode)

PyUnicode_AsUTF8AndSize() とほぼ同じですが、サイズを格納しません。

バージョン 3.3 で追加.

バージョン 3.7 で変更: 返り値の型が char * ではなく const char * になりました。

UTF-32 Codecs

以下は UTF-32 codec API です:

PyObject *PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI.

UTF-32 でエンコードされたバッファ文字列から size バイトをデコードし、 Unicodeオブジェクトとして返します。 errors は (NULL でないなら) エラーハンドラを指定します。デフォルトは "strict" です。

byteorderNULL でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

*byteorder が 0 で、入力データの最初の 4 バイトが byte order mark (BOM) ならば、デコーダはこのバイトオーダーに切り替え、BOM は結果の Unicode 文字列にコピーされません。 *byteorder-1 または 1 ならば、全ての byte order mark は出力にコピーされます。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを *byteorder にセットします。

byteorderNULL のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL のとき、 PyUnicode_DecodeUTF32() と同じように振る舞います。 consumedNULL でないとき、 PyUnicode_DecodeUTF32Stateful() は末尾の不完全な (4 で割り切れない長さのバイト列などの) UTF-32 バイト列をエラーとして扱いません。末尾の不完全なバイト列はデコードされず、デコードされたバイト数が consumed に格納されます。

PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ネイティブバイトオーダーで UTF-32 エンコーディングされた Python バイト文字列を返します。 文字列は常に BOM マークで始まります。 エラーハンドラは "strict" です。 codec が例外を発生させたときは NULL を返します。

UTF-16 Codecs

以下は UTF-16 codec の APIです:

PyObject *PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI.

UTF-16 でエンコードされたバッファ s から size バイトだけデコードして、結果を Unicode オブジェクトで返します。 errors は (NULL でない場合) エラー処理方法を定義します。デフォルト値は "strict" です。

byteorderNULL でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

*byteorder が 0 で、入力データの先頭2バイトがバイトオーダーマーク (BOM) だった場合、デコーダは BOM が示すバイトオーダーに切り替え、そのBOMを結果の Unicode 文字列にコピーしません。 *byteorder-11 だった場合、すべてのBOMは出力へコピーされます (出力では \ufeff\ufffe のどちらかになるでしょう)。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを *byteorder にセットします。

byteorderNULL のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL の場合、 PyUnicode_DecodeUTF16() と同じように動作します。 consumedNULL でない場合、 PyUnicode_DecodeUTF16Stateful() は末尾の不完全な UTF-16 バイト列 (奇数長のバイト列や分割されたサロゲートペア) をエラーとみなしません。これらのバイト列はデコードされず、デコードされたバイト数を consumed に返します。

PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ネイティブバイトオーダーで UTF-16 エンコーディングされた Python バイト文字列を返します。 文字列は常に BOM マークで始まります。 エラーハンドラは "strict" です。 codec が例外を発生させたときは NULL を返します。

UTF-7 Codecs

以下は UTF-7 codec の API です:

PyObject *PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object by decoding size bytes of the UTF-7 encoded string str. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL のとき、 PyUnicode_DecodeUTF7() と同じように動作します。 consumedNULL でないとき、末尾の不完全な UTF-7 base-64 部分をエラーとしません。不完全な部分のバイト列はデコードせずに、デコードしたバイト数を consumed に格納します。

Unicode-Escape Codecs

以下は "Unicode Escape" codec の API です:

PyObject *PyUnicode_DecodeUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object by decoding size bytes of the Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

Raw-Unicode-Escape Codecs

以下は "Raw Unicode Escape" codec の APIです:

PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object by decoding size bytes of the Raw-Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Raw-Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

Latin-1 Codecs

以下は Latin-1 codec の APIです: Latin-1 は、 Unicode 序数の最初の 256 個に対応し、エンコード時にはこの 256 個だけを受理します。

PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

Latin-1 でエンコードされた size バイトの文字列 str から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Latin-1 で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

ASCII Codecs

以下は ASCII codec の APIです。 7 ビットの ASCII データだけを受理します。その他のコードはエラーになります。

PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object by decoding size bytes of the ASCII encoded string str. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ASCII で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

Character Map Codecs

この codec は、多くの様々な codec を実装する際に使われるという点で特殊な codec です (実際、 encodings パッケージに入っている標準 codecs のほとんどは、この codec を使っています)。 この codec は、文字のエンコードやデコードに対応表を使います。 提供される対応表のオブジェクトは __getitem__() マッピングインターフェースをサポートしていなければなりません; 辞書やシーケンスがそれに適しています。

以下は mapping codec の APIです:

PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char *errors)
Return value: New reference. Part of the Stable ABI.

与えられた mapping オブジェクトを使って、 size バイトのエンコードされた文字列 str をデコードして Unicode オブジェクトを作成します。 codec が例外を発生させたときは NULL を返します。

If mapping is NULL, Latin-1 decoding will be applied. Else mapping must map bytes ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None. Unmapped data bytes -- ones which cause a LookupError, as well as ones which get mapped to None, 0xFFFE or '\ufffe', are treated as undefined mappings and cause an error.

PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI.

Unicode オブジェクトを mapping に指定されたオブジェクトを使ってエンコードし、結果を bytes オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

The mapping object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are treated as "undefined mapping" and cause an error.

以下の codec API は Unicode から Unicode への対応付けを行う特殊なものです。

PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI.

文字列に文字対応表 table を適用して変換し、変換結果を Unicode オブジェクトで返します。codec が例外を発行した場合には NULL を返します。

対応表は、Unicode 序数を表す整数を Unicode 序数を表す整数または None (その文字を削除する) に対応付けなければなりません。

Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.

errors は codecs で通常使われるのと同じ意味を持ちます。 errorsNULL にしてもよく、デフォルトエラー処理の使用を意味します。

Windows 用の MBCS codec

以下は MBCS codec の API です。この codec は現在のところ、 Windows 上だけで利用でき、変換の実装には Win32 MBCS 変換機構 (Win32 MBCS converter) を使っています。 MBCS (または DBCS) はエンコード方式の種類 (class) を表す言葉で、単一のエンコード方式を表すわけでなないので注意してください。利用されるエンコード方式 (target encoding) は、 codec を動作させているマシン上のユーザ設定で定義されています。

PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

Create a Unicode object by decoding size bytes of the MBCS encoded string str. Return NULL if an exception was raised by the codec.

PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

consumedNULL のとき、 PyUnicode_DecodeMBCS() と同じ動作をします。 consumedNULL でないとき、 PyUnicode_DecodeMBCSStateful() は文字列の最後にあるマルチバイト文字の前半バイトをデコードせず、 consumed にデコードしたバイト数を格納します。

PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

MBCS で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

Encode the Unicode object using the specified code page and return a Python bytes object. Return NULL if an exception was raised by the codec. Use CP_ACP code page to get the MBCS encoder.

バージョン 3.3 で追加.

メソッドとスロット

メソッドおよびスロット関数 (slot function)

以下の API は Unicode オブジェクトおよび文字列を入力に取り (説明では、どちらも文字列と表記しています)、場合に応じて Unicode オブジェクトか整数を返す機能を持っています。

これらの関数は全て、例外が発生した場合には NULL または -1 を返します。

PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Return value: New reference. Part of the Stable ABI.

二つの文字列を結合して、新たな Unicode 文字列を生成します。

PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI.

Unicode 文字列のリストを分割して、 Unicode 文字列からなるリストを返します。 sepNULL の場合、全ての空白文字を使って分割を行います。それ以外の場合、指定された文字を使って分割を行います。最大で maxsplit 個までの分割を行います。 maxsplit が負ならば分割数に制限を設けません。分割結果のリスト内には分割文字は含みません。

PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
Return value: New reference. Part of the Stable ABI.

Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If keepends is 0, the Line break characters are not included in the resulting strings.

PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI.

指定した separator で文字列からなるシーケンスを連結 (join) し、連結結果を Unicode 文字列で返します。

Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI.

Return 1 if substr matches unicode[start:end] at the given tail end (direction == -1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.

Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI.

unicode[start:end] 中に substr が最初に出現する場所を返します。 このとき指定された検索方向 direction (direction == 1 は順方向検索、 direction == -1 は逆方向検索) で検索します。 戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 -1 はマッチが見つからなかったことを表し、 -2 はエラーが発生して例外情報が設定されていることを表します。

Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI since version 3.7.

unicode[start:end] 中に文字 ch が最初に出現する場所を返します。 このとき指定された検索方向 direction (direction == 1 は順方向検索、 direction == -1 は逆方向検索) で検索します。 戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 -1 はマッチが見つからなかったことを表し、 -2 はエラーが発生して例外情報が設定されていることを表します。

バージョン 3.3 で追加.

バージョン 3.7 で変更: start and end are now adjusted to behave like unicode[start:end].

Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI.

unicode[start:end]substr が重複することなく出現する回数を返します。エラーが発生した場合には -1 を返します。

PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
Return value: New reference. Part of the Stable ABI.

unicode 中に出現する substr を最大で maxcountreplstr に置換し、置換結果である Unicode オブジェクトを返します。 maxcount == -1 にすると、文字列中に現れる全ての substr を置換します。

int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI.

二つの文字列を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ -1, 0, 1 を返します。

この関数は、失敗したときに -1 を返すので、 PyErr_Occurred() を呼び出して、エラーをチェックすべきです。

int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Part of the Stable ABI.

Unicode オブジェクト unicodestring を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ -1, 0, 1 を返します。 ASCII エンコードされた文字列だけを渡すのが最も良いですが、入力文字列に非 ASCII 文字が含まれている場合は ISO-8859-1 として解釈します。

この関数は例外を送出しません。

PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Return value: New reference. Part of the Stable ABI.

二つのUnicode文字列を比較して、下のうちの一つを返します:

  • NULL を、例外が発生したときに返します。

  • Py_True もしくは Py_False を、正しく比較できた時に返します。

  • Py_NotImplemented in case the type combination is unknown

Possible values for op are Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE.

PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
Return value: New reference. Part of the Stable ABI.

新たな文字列オブジェクトを format および args から生成して返します; このメソッドは format % args のようなものです。

int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
Part of the Stable ABI.

substrunicode 内にあるか調べ、その結果に応じて真または偽を返します。

substr は単要素の Unicode 文字に型強制できなければなりません。エラーが生じた場合には -1 を返します。

void PyUnicode_InternInPlace(PyObject **p_unicode)
Part of the Stable ABI.

Intern the argument *p_unicode in place. The argument must be the address of a pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as *p_unicode, it sets *p_unicode to it (releasing the reference to the old string object and creating a new strong reference to the interned string object), otherwise it leaves *p_unicode alone and interns it (creating a new strong reference). (Clarification: even though there is a lot of talk about references, think of this function as reference-neutral; you own the object after the call if and only if you owned it before the call.)

PyObject *PyUnicode_InternFromString(const char *str)
Return value: New reference. Part of the Stable ABI.

PyUnicode_FromString()PyUnicode_InternInPlace() を組み合わせたもので、収容済みの新たな文字列オブジェクトを返すか、同じ値を持つ収容済みの Unicode 文字列オブジェクトに対する新たな ("所有権のある") 参照を返します。