Python ਕੋਲ dynamic values ਦੇ ਨਾਲ strings ਬਣਾਉਣ ਦੇ ਕਈ ਤਰੀਕੇ ਹਨ। ਆਧੁਨਿਕ, ਸਿਫ਼ਾਰਿਸ਼ ਕੀਤਾ ਤਰੀਕਾ f-string (formatted string literal) ਹੈ, ਜੋ Python 3.6 ਵਿੱਚ ਪੇਸ਼ ਕੀਤਾ ਗਿਆ ਸੀ।
f-strings — ਆਧੁਨਿਕ ਮਾਨਦੰਡ
name =
age =
msg =
f prefix ਤੁਹਾਨੂੰ {} ਵਿਚ ਸਿੱਧਾ expressions embed ਕਰਨ ਦੇਦਾ ਹੈ — ਸੰਖੇਪ, ਪੜ੍ਹਨ ਯੋਗ, ਅਤੇ ਤੇਜ਼। ਇਹ ਆਧੁਨਿਕ Python ਵਿੱਚ ਪਸੰਦਵੀਂ ਵਿਧੀ ਹੈ।
f"{3.14159:.2f}" # "3.14" — 2 decimal places
f"{1000000:,}" # "1,000,000" — thousands separator
f"{0.85:.1%}" # "85.0%" — percentage
f"{42:05d}" # "00042" — pad with zeros to width 5
f"{'hi':>10}" # " hi" — right-align in width 10
f"{'hi':^10}" # " hi " — center
Value ਦੇ ਬਾਅਦ :spec precision, padding, alignment, ਅਤੇ number formatting ਨੂੰ ਕੰਟਰੋਲ ਕਰਦਾ ਹੈ — ਸਾਫ output ਲਈ ਤਾਕਤਵਰ।
f"{name=}" # "name='Ann'" — prints both the expression AND value
= ਤੇਜ਼ debugging ਲਈ ਆਸਾਨ ਹੈ — ਇਹ variable name ਅਤੇ ਇਸ ਦੀ value ਦਿਖਾਉਂਦਾ ਹੈ।
"{} is {}".format(name, age) # str.format() — pre-f-string standard
"%s is %d" % (name, age) # %-formatting — old C-style (avoid in new code)
name + " is " + str(age) # concatenation — verbose, error-prone
.format() ਪੁਰਾਣੇ code ਵਿੱਚ ਹਿਜੀ ਆਮ ਹੈ; %-formatting legacy ਹੈ; raw concatenation ਨੂੰ discourage ਕੀਤਾ ਜਾਂਦਾ ਹੈ (wordy ਅਤੇ manual str() conversion ਦੀ ਲੋੜ ਹੈ)।
String formatting ਲਗਾਤਾਰ ਲੋੜੀਂਦਾ ਹੈ — messages, logs, output, queries ਬਣਾਉਣ ਲਈ।
F-strings ਆਧੁਨਿਕ, ਪੜ੍ਹਨ ਯੋਗ, ਅਤੇ ਕੁਸ਼ਲ ਮਾਨਦੰਡ ਹਨ, ਅਤੇ ਉਨ੍ਹਾਂ ਦੀ format specifiers (precision, padding, alignment, separators) ਨੂੰ ਜਾਨਣਾ ਤੁਹਾਨੂੰ wordy code ਤੋਂ ਬਿਨਾਂ ਸਾਫ, ਪੇਸ਼ੇਵਰ output ਪੈਦਾ ਕਰਨ ਦਿੰਦਾ ਹੈ।
ਪੁਰਾਣੀ .format() ਅਤੇ % styles ਨੂੰ ਪਛਾਣਨਾ ਮੌਜੂਦਾ codebases ਨੂੰ ਪੜ੍ਹਦੇ ਸਮੇਂ ਮਦਦ ਕਰਦਾ ਹੈ।
f-strings ਨੂੰ ਚੰਗੀ ਤਰ੍ਹਾਂ ਵਰਤਣਾ ਸਪਸ਼ਟ, idiomatic Python ਲਿਖਣ ਦਾ ਛੋਟਾ ਪਰ ਵਿਆਪਕ ਹਿੱਸਾ ਹੈ।