・文字列のゼロ埋め
与えられた文字列に対して、左側にゼロ、もしくは他の文字を埋め込むにはrjust関数を利用します。
例えば「rjust(10,"0")」の場合、総文字数が10になるように左側に0を埋め込みます。
第二引数は0でなくても問題ありません。
スクリプト
実行結果
また、zfillという関数を利用してゼロを埋め込むことも出来ます。
なお、引数の値より、文字数が大きい場合は特に何も起きません。
スクリプト
実行結果
・文字列の検索
先頭の文字が指定された文字列かを調べるにはstartswith関数を利用します。
結果はtrueかfalseで返ります。
スクリプト
実行結果
もしくはin関数を利用する方法もあります。
「検索文字列 in 検索対象」という感じになります。
スクリプト
実行結果
与えられた文字列に対して、左側にゼロ、もしくは他の文字を埋め込むにはrjust関数を利用します。
例えば「rjust(10,"0")」の場合、総文字数が10になるように左側に0を埋め込みます。
第二引数は0でなくても問題ありません。
スクリプト
# -*- coding: utf-8 -*-
test_str = "1234"
print (test_str.rjust(10,"0"))
print (test_str.rjust(10,"!")) 実行結果
0000001234
!!!!!!1234 また、zfillという関数を利用してゼロを埋め込むことも出来ます。
なお、引数の値より、文字数が大きい場合は特に何も起きません。
スクリプト
# -*- coding: utf-8 -*-
test_str = "1234"
print (test_str.zfill(10))
print (test_str.zfill(3))
実行結果
0000001234
1234
・文字列の検索
先頭の文字が指定された文字列かを調べるにはstartswith関数を利用します。
結果はtrueかfalseで返ります。
スクリプト
# -*- coding: utf-8 -*-
test_str = "python-izm"
print (test_str.startswith("python"))
print (test_str.startswith("izm")) 実行結果
True
False もしくはin関数を利用する方法もあります。
「検索文字列 in 検索対象」という感じになります。
スクリプト
# -*- coding: utf-8 -*-
test_str = "python-izm"
print ("z" in test_str)
print ("s" in test_str) 実行結果
True
False
・大文字、小文字変換
大文字の変換はupper関数、小文字の変換はlower関数を利用します。
スクリプト
実行結果
・先頭、末尾の文字列削除
先頭の文字列を削除する場合はlstrip関数、末尾の文字列を削除するにはrstrip関数を利用します。
引数を指定してない場合は空白を除去します。
スクリプト
・大文字、小文字変換
大文字の変換はupper関数、小文字の変換はlower関数を利用します。
スクリプト
# -*- coding: utf-8 -*-
test_str = "Python-Izm"
print (test_str.upper())
print (test_str.lower()) 実行結果
PYTHON-IZM
python-izm ・先頭、末尾の文字列削除
先頭の文字列を削除する場合はlstrip関数、末尾の文字列を削除するにはrstrip関数を利用します。
引数を指定してない場合は空白を除去します。
スクリプト
# -*- coding: utf-8 -*-
test_str = " Python-Izm"
print (test_str)
test_str = test_str.lstrip()
print (test_str)
test_str = test_str.lstrip("Python")
print (test_str)
test_str = test_str.rstrip("Izm")
print (test_str)
実行結果
実行結果
Python-Izm
Python-Izm
-Izm
-
コメント