Python 2 および 3 で文字列を小文字に変換する方法

Python 3 で文字列を小文字に変換する
Python 3.0 はデフォルトで Unicode
文字を含むため、str
タイプ。"unicode example"
、'unicode example 2'
などの文字列は Unicode
として保存されます。
したがって、Python 3 では、str.lower()
を使用して任意の文字列を小文字に変換できます。
exampleString = "CaseString"
exampleString.lower()
#Out: 'casestring'
exampleString = "СтрокаСлучая"
exampleString.lower()
#Out: 'строкаслучая'
str.casefold()
ケースレス変換
str.lower()
は文字列を小文字に変換しますが、文字列の大文字と小文字の区別は変換しません。
たとえば、ドイツ語のß
はダブル s
-ss
に等しく、ß
自体はすでに小文字であるため、str.lower()
はそれを変換しません。
しかし、str.casefold()
は ß
を ss
に変換します。
>>> 'Straße'.lower()
'straße'
>>> 'Straße'.casefold()
'strasse'
Python 2.7 で文字列を小文字に変換する
Python 2.7 の str
型は Unicode
として保存されず、Unicode
文字列は unicode
型のインスタンスです。文字列を小文字に変換するとき、文字列が ASCII
文字列か unicode
文字列かを区別する必要があります。
ASCII
タイプ
Python 3 で使用されるメソッドと同じです。str.lower()
は文字列を小文字に変換します。
exampleString = "CaseStringExample"
exampleString.lower()
#Out: 'casestringexample'
unicode
タイプ
文字列の文字が Unicode
型で、文字列が Unicode
型で明示的に表されていない場合、str.lower()
メソッドは文字列を小文字に変換しません。
exampleString = "СтрокаСлучая"
print exampleString.lower()
#Out: СтрокаСлучая
exampleString.lower() == exampleString
#Out: True
Python は、意図されたコーディングが暗黙的であるため、エンコードなしの文字列内の非 ASCII バイトに反対します。
str
ではなく Unicode
リテラルを使用
exampleUnicodeString = u"СтрокаСлучая"
exampleUnicode
#u'\u0421\u0442\u0440\u043e\u043a\u0430\u0421\u043b\u0443\u0447\u0430\u044f'
exampleUnicodeString.lower()
#u'\u0441\u0442\u0440\u043e\u043a\u0430\u0441\u043b\u0443\u0447\u0430\u044f'
print exampleUnicodeString.lower()
#Out: строкаслучая
ここで、文字列の最初の文字が \u0421
から \u0441
に変換されていることがわかります。
str
を unicode
に変換する
与えられた文字列が str
の形式である場合、小文字に変換する前にまず Unicode
に変換する必要があります。
exampleString = "СтрокаСлучая"
print exampleString.decode('utf-8').lower()
#Out: строкаслучая
まとめ
lower()
メソッドは、Python 2 と 3 の両方で文字列を小文字に変換するメソッドですが、顕著な違いがあります。
Python 3 の文字列はデフォルトでは unicode
文字列ですが、Python 2 の文字列はそうではありません。文字列の前に u
を入れないなど、文字列が明示的に unicode
型として表されていない場合、Unicode 文字列は小文字に変換されません。
str.casefold
は大文字と小文字の区別を大文字と小文字を区別しない一致に変換しますが、Python 3 でのみ使用可能です。py2casefold を Python 2 にインストールできます。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn