%s
Pythonではどういう意味ですか?そして、次のコードは何をしますか?
例えば...
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
%s
Pythonではどういう意味ですか?そして、次のコードは何をしますか?
例えば...
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
これは文字列フォーマット構文です(Cから借用しています)。
「PyFormat」をご覧ください:
Pythonは、値の文字列へのフォーマットをサポートしています。
%s
これには非常に複雑な式が含まれる場合がありますが、最も基本的な使用法は、プレースホルダーを使用して文字列に値を挿入することです。
これは本当に簡単な例です:
#Python 2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python 3+
name = input("who are you? ")
print("hello %s" % (name,))
トークンを使用すると、文字列を挿入(および場合によっては%s
フォーマット)できます。トークンは、シンボル%s
の後の文字列に渡すものに置き換えられていることに注意してください。%
ここでもタプルを使用していることにも注意してください(タプルを使用する文字列が1つしかない場合はオプションです)。これは、1つのステートメントに複数の文字列を挿入してフォーマットできることを示しています。
アンドリューの答えは良いです。
そして、もう少し役立つように、1つの文字列で複数のフォーマットを使用する方法を次に示します。
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
文字列の代わりにintを使用している場合は、%sの代わりに%dを使用してください。
"My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12
このformat
メソッドはPython2.6で導入されました。それはより能力があり、使用するのはそれほど難しくありません:
>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.
>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'
>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'
>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'
%s
および%d
は、文字列、小数、浮動小数点数などをフォーマットするためのフォーマット指定子またはプレースホルダーです。
最も一般的に使用されるフォーマット指定子:
%s
: ストリング
%d
:小数
%f
: 浮く
自明のコード:
name = "Gandalf"
extendedName = "the Grey"
age = 84
IQ = 149.9
print('type(name): ', type(name)) # type(name): <class 'str'>
print('type(age): ', type(age)) # type(age): <class 'int'>
print('type(IQ): ', type(IQ)) # type(IQ): <class 'float'>
print('%s %s\'s age is %d with incredible IQ of %f ' %(name, extendedName, age, IQ)) # Gandalf the Grey's age is 84 with incredible IQ of 149.900000
# The same output can be printed in following ways:
print ('{0} {1}\'s age is {2} with incredible IQ of {3} '.format(name, extendedName, age, IQ)) # With the help of an older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ)) # With the help of an older method
print("Multiplication of %d and %f is %f" %(age, IQ, age*IQ)) # Multiplication of 84 and 149.900000 is 12591.600000
# Storing formattings in a string
sub1 = "python string!"
sub2 = "an arg"
a = "I am a %s" % sub1
b = "I am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print(a) # "I am a python string!"
print(b) # "I am a python string!"
print(c) # "with an arg!"
print(d) # "with an arg!"
%s
Pythonの文字列フォーマット機能を使用する場合の文字列の変換タイプを示します。具体的には%s
、関数を使用して指定した値を文字列に変換しますstr()
。これを、値変換の関数を%r
使用する変換タイプと比較してください。repr()
文字列のフォーマットについては、ドキュメントをご覧ください。
2番目の質問に答えるには:このコードは何をしますか?...
これは、コマンドライン引数を受け入れるPythonスクリプトのかなり標準的なエラーチェックコードです。
したがって、最初のif
ステートメントは次のように解釈されます。引数を渡していない場合は、将来どのように引数を渡すべきかを説明します。たとえば、画面に次のように表示されます。
Usage: myscript.py database-name
次のif
ステートメントは、スクリプトに渡した「データベース名」が実際にファイルシステムに存在するかどうかを確認します。そうでない場合は、次のようなメッセージが表示されます。
エラー:データベースデータベース名が見つかりませんでした!
ドキュメントから:
argv [0]はスクリプト名です(これがフルパス名であるかどうかはオペレーティングシステムによって異なります)。インタプリタに対して-cコマンドラインオプションを使用してコマンドが実行された場合、argv[0]は文字列'-c'に設定されます。スクリプト名がPythonインタープリターに渡されなかった場合、argv[0]は空の文字列です。
これがPython3の良い例です。
>>> a = input("What is your name?")
What is your name?Peter
>>> b = input("Where are you from?")
Where are you from?DE
>>> print("So you are %s of %s" % (a, b))
So you are Peter of DE