0

new to python and programming in general. Forr the following code, why would 'a''b''c''d' be printed separately for each loop, I understand that 'abcd' would be treated as an array but does putting it in curly braces have a special meaning? Is this a function unique to python?

for i in range(4):
    print(f"{'abcd'[i]}")

Was just wondering about how exactly f strings and the curly braces work.

azro
  • 53,056
  • 7
  • 34
  • 70
duckpro
  • 17
  • 2
  • nothing to do with `f` strings, you're indexing that array with `[i]`, `i` is the index and at any given iteration it's one of `0, 1, 2, 3` – Matiiss Jan 29 '23 at 11:19
  • 2
    your code is same if you do `print('abcd'[i])` – azro Jan 29 '23 at 11:20

1 Answers1

1

Was just wondering about how exactly f strings and the curly braces work.

This is described by Abstract of PEP 498 – Literal String Interpolation following way

(...)F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces. The expressions are replaced with their values.(...)

Is this a function unique to python?

No. Recent versions of JavaScript have similar feature named Template strings which are enclosed in backtick characters, for example

let letters = "abcd";
for(i=0;i<letters.length;i+=1){
    console.log(`Letter ${letters[i]}`)
}

make console output

Letter a
Letter b
Letter c
Letter d
Daweo
  • 31,313
  • 3
  • 12
  • 25