私はfront_back google pythonの演習の解説を探しています。具体的には、なぜ%記号(プレースホルダ?)が使われているのか分かりません。文字列の長さを2で割っている理由私はまた2が等しい1(2 == 1×)しない、特に以来あなたはfront_back google pythonの演習への解決策を説明できますか
を理解していない問題/解決策は以下の通りである:
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
# +++your code here+++
# LAB(begin solution)
# Figure out the middle position of each string.
a_middle = len(a)/2
b_middle = len(b)/2
if len(a) % 2 == 1: # add 1 if length is odd
a_middle = a_middle + 1
if len(b) % 2 == 1:
b_middle = b_middle + 1
return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
# LAB(replace solution)
# return
# LAB(end solution)
ありがとうございました!
%はプレースホルダではありません。それはモジュロ演算子です。上のコメントは、その行が何をしているかを示しています。そしてコメントは、なぜ2による除算が行われているのかを正確に示しています。私はPythonのチュートリアルの1つを見つけることをお勧めします。 python.orgにそれらのリストがあります。 (少なくとも、あなたが投稿したコードのコメントを読むべきです。物事を非常にはっきりと説明していますが、実際にその中の言葉を読む必要があります。) –
@KenWhiteは、モジュロ演算子が何であるかに精通しています。これは妥当な質問でした。 – SandPiper