Python文字列メソッド?
Pythonには、文字列で使用できる多くの組み込みメソッドが用意されています。
以下は、Python3で使用可能な文字列メソッドのリストです。
| メソッド | 説明 | 例 |
| Capitalize() | 最初の文字を大文字にし、残りを小文字にした文字列のコピーを返します。 | >>> mystring = "hello python" >>> print(mystring.capitalize()) Hello python |
| Casefold() | 文字列の大文字と小文字を区別したコピーを返します。大文字と小文字を区別しない文字列は、大文字と小文字を区別しないマッチングに使用できます。 | >>> mystring = "hello PYTHON" >>> print(mystring.casefold()) hello python |
| Center(width、[fillchar]) | 長さ幅の文字列の中央にある文字列を返します 。パディングは、指定された fillcharを使用して実行できます。 (デフォルトのパディングはASCIIスペースを使用します)。 width の場合、元の文字列が返されます len(s)以下 | >>> mystring = "Hello" >>> x = mystring.center(12, "-") >>> print(x) ---Hello---- |
| Count(sub、[start]、[end]) | 重複しない部分文字列の出現回数を返します( sub )範囲[ start 、終了 ]。オプションの引数start および終了 スライス表記のように解釈されます。 | >>> mystr = "Hello Python"
>>> print(mystr.count("o"))
2
>>> print(mystr.count("th"))
1
>>> print(mystr.count("l"))
2
>>> print(mystr.count("h"))
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0 |
| Encode(encoding =“ utf-g”、errors =“ strict”) | >>> mystr = 'python!'
>>> print('The string is:',
mystr)
The string is: python!
>>> print('The encoded
version is: ',
mystr.encode("ascii",
"ignore"))
The encoded version is:
b'python!'
>>> print('The encoded
version (with replace) is:',
mystr.encode("ascii",
"replace"))
The encoded version (with
replace) is: b'python!' | |
| endswith(suffix、[start]、[end]) | 文字列が指定されたサフィックスで終わる場合はTrueを返し、そうでない場合はFalseを返します。 | >>> mystr = "Python"
>>>
print(mystr.endswith("y"))
False
>>>
print(mystr.endswith("hon"))
True |
| Expandtabs(tabsize =8) | 現在の列と指定されたタブサイズに応じて、すべてのタブ文字が1つ以上のスペースに置き換えられた文字列のコピーを返します。 | >>> mystr = "1\t2\t3" >>> print(mystr) 1 2 3 >>> print(mystr.expandtabs()) 1 2 3 >>> print(mystr.expandtabs(tabsi ze=15)) 1 2 3 >>> print(mystr.expandtabs(tabsi ze=2)) 1 2 3 |
| Find(sub、[start]、[end]) | substring subの文字列の中で最も低いインデックスを返します スライスs[start:end]内にあります。 | >>> mystring = "Python"
>>>
print(mystring.find("P"))
0
>>>
print(mystring.find("on"))
4 |
| Format(* args、** kwargs) | 文字列のフォーマット操作を実行します。このメソッドが呼び出される文字列には、中括弧{}で区切られたリテラルテキストまたは置換フィールドを含めることができます。 | >>> print("{} and
{}".format("Apple",
"Banana"))
Apple and Banana
>>> print("{1} and
{0}".format("Apple",
"Banana"))
Banana and Apple
>>> print("{lunch} and
{dinner}".format(lunch="Peas
", dinner="Beans"))
Peas and Beans |
| format_map(mapping) | マッピングが直接使用され、辞書にコピーされないことを除いて、format(** mapping)と同様です。 | >>> lunch = {"Food":
"Pizza", "Drink": "Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(lunch))
Lunch: Pizza, Wine
>>> class Default(dict):
def __missing__(self,
key):
return key
>>> lunch = {"Drink":
"Wine"}
>>> print("Lunch: {Food},
{Drink}".format_map(Default(
lunch)))
Lunch: Food, Wine |
| Index(sub、[start]、[end]) | 文字列で指定された値を検索し、見つかった場所の位置を返します | >>> mystr = "HelloPython"
>>> print(mystr.index("P"))
5
>>>
print(mystr.index("hon"))
8
>>> print(mystr.index("o"))
4 |
| isalnum | 文字列内のすべての文字が英数字の場合はTrueを返します | >>> mystr = "HelloPython" >>> print(mystr.isalnum()) True >>> a = "123" >>> print(a.isalnum()) True >>> a= "$*%!!!" >>> print(a.isalnum()) False |
| Isalpha() | 文字列内のすべての文字がアルファベットの場合はTrueを返します | >>> mystr = "HelloPython" >>> print(mystr.isalpha()) True >>> a = "123" >>> print(a.isalpha()) False >>> a= "$*%!!!" >>> print(a.isalpha()) False |
| Isdecimal() | 文字列内のすべての文字が小数の場合はTrueを返します | >>> mystr = "HelloPython" >>> print(mystr.isdecimal()) False >>> a="1.23" >>> print(a.isdecimal()) False >>> c = u"\u00B2" >>> print(c.isdecimal()) False >>> c="133" >>> print(c.isdecimal()) True |
| Isdigit() | 文字列内のすべての文字が数字の場合はTrueを返します | >>> c="133" >>> print(c.isdigit()) True >>> c = u"\u00B2" >>> print(c.isdigit()) True >>> a="1.23" >>> print(a.isdigit()) False |
| isidentifier() | 文字列が識別子の場合はTrueを返します | >>> c="133" >>> print(c.isidentifier()) False >>> c="_user_123" >>> print(c.isidentifier()) True >>> c="Python" >>> print(c.isidentifier()) True |
| Islower() | 文字列内のすべての文字が小文字の場合はTrueを返します | >>> c="Python" >>> print(c.islower()) False >>> c="_user_123" >>> print(c.islower()) True >>> print(c.islower()) False |
| Isnumeric() | 文字列内のすべての文字が数字の場合はTrueを返します | >>> c="133" >>> print(c.isnumeric()) True >>> c="_user_123" >>> print(c.isnumeric()) False >>> c="Python" >>> print(c.isnumeric()) False |
| isprintable() | 文字列内のすべての文字が印刷可能である場合はTrueを返します | >>> c="133" >>> print(c.isprintable()) True >>> c="_user_123" >>> print(c.isprintable()) True >>> c="\t" >>> print(c.isprintable()) False |
| isspace() | 文字列内のすべての文字が空白の場合はTrueを返します | >>> c="133" >>> print(c.isspace()) False >>> c="Hello Python" >>> print(c.isspace()) False 73 >>> c="Hello" >>> print(c.isspace()) False >>> c="\t" >>> print(c.isspace()) True |
| istitle() | 文字列がタイトルのルールに従っている場合はTrueを返します | >>> c="133" >>> print(c.istitle()) False >>> c="Python" >>> print(c.istitle()) True >>> c="\t" >>> print(c.istitle()) False |
| isupper() | 文字列内のすべての文字が大文字の場合はTrueを返します | >>> c="Python" >>> print(c.isupper()) False >>> c="PYHTON" >>> print(c.isupper()) True >>> c="\t" >>> print(c.isupper()) False |
| join(iterable) | 文字列の最後に反復可能な要素を結合します | >>> a ="-"
>>> print(a.join("123"))
1-2-3
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello
Python"))
H**e**l**l**o**
**P**y**t**h**o**n |
| ljust( 幅 [、 fillchar ]) | 文字列の左寄せバージョンを返します | >>> a="Hello" >>> b = a.ljust(12, "_") >>> print(b) Hello_______ |
| lower() | 文字列を小文字に変換します | >>> a = "Python" >>> print(a.lower()) Python |
| lstrip([ 文字 ]) | 文字列の左トリムバージョンを返します | >>> a = " Hello " >>> print(a.lstrip(), "!") Hello |
| maketrans( x [、 y [、 z ]]) | 翻訳で使用される翻訳テーブルを返します | >>> frm = "SecretCode" >>> to = "4203040540" >>> trans_table = str.maketrans(frm,to) >>> sec_code = "Secret Code".translate(trans_table) >>> print(sec_code) 400304 0540 |
| パーティション( 9月 ) | 文字列が3つの部分に分割されているタプルを返します | >>> mystr = "Hello-Python"
>>> print(mystr.partition("-
"))
('Hello', '-', 'Python')
74
>>>
print(mystr.partition("."))
('Hello-Python', '', '') |
| replace( 古い 、 新しい [、 カウント ]) | 指定された値が指定された値に置き換えられた文字列を返します | >>> mystr = "Hello Python.
Hello Java. Hello C++."
>>>
print(mystr.replace("Hello",
"Bye"))
Bye Python. Bye Java. Bye
C++.
>>>
print(mystr.replace("Hello",
"Hell", 2))
Hell Python. Hell Java.
Hello C++. |
| rfind( サブ [、 開始 [、 終了 ]]) | 文字列で指定された値を検索し、見つかった場所の最後の位置を返します | >>> mystr = "Hello-Python"
>>> print(mystr.rfind("P"))
6
>>> print(mystr.rfind("-"))
5
>>> print(mystr.rfind("z"))
-1 |
| rindex( サブ [、 開始 [、 終了 ]]) | 文字列で指定された値を検索し、見つかった場所の最後の位置を返します | >>> mystr = "Hello-Python"
>>> print(mystr.rindex("P"))
6
>>> print(mystr.rindex("-"))
5
>>> print(mystr.rindex("z"))
Traceback (most recent call
last):
File "<pyshell#253>", line
1, in <module>
print(mystr.rindex("z"))
ValueError: substring not
found> |
| rjust( 幅 [、 fillchar ]) | 長さ幅の文字列で右寄せされた文字列を返します 。 | >>> mystr = "Hello Python" >>> mystr1 = mystr.rjust(20, "-") >>> print(mystr1) --------Hello Python> |
| rpartition( 9月 ) | 文字列が3つの部分に分割されているタプルを返します | >>> mystr = "Hello Python"
>>>
print(mystr.rpartition("."))
('', '', 'Hello Python')
>>> print(mystr.rpartition("
"))
('Hello', ' ', 'Python') |
| rsplit(sep =None、maxsplit =-1) | 指定された区切り文字で文字列を分割し、リストを返します | >>> mystr = "Hello Python" >>> print(mystr.rsplit()) ['Hello', 'Python'] >>> mystr = "Hello-Python- Hello" >>> print(mystr.rsplit(sep="-", maxsplit=1)) ['Hello-Python', 'Hello'] |
| rstrip([ 文字 ]) | 文字列の右トリムバージョンを返します | >>> mystr = "Hello Python" >>> print(mystr.rstrip(), "!") Hello Python ! >>> mystr = "------------ Hello Python-----------" >>> print(mystr.rstrip(), "- ") ------------Hello Python---- ------- - >>> print(mystr.rstrip(), "_") ------------Hello Python---- ------- _> |
| split(sep =None、maxsplit =-1) | 指定された区切り文字で文字列を分割し、リストを返します | >>> mystr = "Hello Python"
>>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python'] |
| splitlines([keepends]) | 改行で文字列を分割し、リストを返します | >>> mystr = "Hello:\n\n Python\r\nJava\nC++\n" >>> print(mystr.splitlines()) ['Hello:', '', ' Python', 'Java', 'C++'] >>> print(mystr.splitlines(keepe nds=True)) ['Hello:\n', '\n', ' Python\r\n', 'Java\n', 'C++\n'] |
| startwith( プレフィックス [、 開始 [、 終了 ]]) | 文字列が指定された値で始まる場合はtrueを返します | >>> mystr = "Hello Python"
>>>
print(mystr.startswith("P"))
False
>>>
print(mystr.startswith("H"))
True
>>>
print(mystr.startswith("Hell
"))
True |
| strip([ 文字 ]) | 文字列のトリミングされたバージョンを返します | >>> mystr = " Hello Python " >>> print(mystr.strip(), "!") Hello Python ! >>> print(mystr.strip(), " ") Hello Python |
| swapcase() | 大文字と小文字を入れ替えると、小文字が大文字になり、その逆も同様です。 | >>> mystr = "Hello PYthon" >>> print(mystr.swapcase()) hELLO python |
| title() | 各単語の最初の文字を大文字に変換します | >>> mystr = "Hello PYthon" >>> print(mystr.title()) Hello Python >>> mystr = "HELLO JAVA" >>> print(mystr.title()) Hello Java |
| translate( テーブル ) | 翻訳された文字列を返します | >>> frm = "helloPython" >>> to = "40250666333" >>> trans_table = str.maketrans(frm, to) >>> secret_code = "Secret Code".translate(trans_table) >>> print(secret_code) S0cr06 C3d0 |
| upper() | 文字列を大文字に変換します | >>> mystr = "hello Python" >>> print(mystr.upper()) HELLO PYTHON |
| zfill( 幅 ) | 最初に指定された数の0値で文字列を埋めます | >>> mystr = "999" >>> print(mystr.zfill(9)) 000000999 >>> mystr = "-40" >>> print(mystr.zfill(5)) -0040 |
-
PythonのDunderまたはmagicメソッド
オブジェクト指向プログラミングでかなり巧妙なトリックを実行できる魔法のメソッド。これらのメソッドは、プレフィックスとサフィックスとして使用される2つのアンダースコア(__)で識別されます。例として、特定の条件が満たされたときに自動的に呼び出されるインターセプターとして機能します。 Pythonでは、__ repr__はオブジェクトの「公式」文字列表現を計算するために使用される組み込み関数であり、__str__はオブジェクトの「非公式」文字列表現を計算する組み込み関数です。 サンプルコード class String: # magic method to initiate obj
-
Pythonで連結文字列を印刷するにはどうすればよいですか?
文字列とともに使用する場合、プラス(+)は連結演算子として定義されます。最初の文字列に2番目の文字列を追加します。 >>> s1 = TutorialsPoint >>> s2 = Hyderabad >>> print (s1+s2) TutorialsPoint Hyderabad