テキスト1の文字列照合文字列の先頭や末尾 - マスターSEVENへのエントリからPythonの戦闘

そのようなファイル名の接尾辞として指定したテキストモード、URLスキームによって、文字列の先頭や末尾にチェックし、そうです。

文字列の先頭や末尾をチェックする簡単な方法は、使用である  str.startswith() か  str.endswith() の方法。例えば:

>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True

複数の一致チェックはタプルにマッチのすべてを配置する必要があり、その後、渡されたこと  startswith()や  endswith() 方法:

>>> import os
>>> filenames = os.listdir('.')
>>> filenames
[ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ]
>>> [name for name in filenames if name.endswith(('.c', '.h')) ]
['foo.c', 'spam.c', 'spam.h'
>>> any(name.endswith('.py') for name in filenames)
True

startswith() そして、  endswith() この方法では、それは文字列の先頭と末尾をチェック行うには非常に便利な方法を提供します。同様の動作も実現するためにスライスを使用することができますが、コードはとてもエレガントでいないようです。例えば:

>>> filename = 'spam.txt'
>>> filename[-4:] == '.txt'
True
>>> url = 'http://www.python.org'
>>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:'
True

 

公開された336元の記事 ウォンの賞賛170 ビュー500 000 +

おすすめ

転載: blog.csdn.net/qq_32146369/article/details/104211121