[{"data":1,"prerenderedAt":74},["ShallowReactive",2],{"qa-\u002Fpython\u002Ffundamentals\u002Fstrings-formatting":3},{"page":4,"siblings":57,"blog":48},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":48,"seo":49,"seoDescription":50,"stem":51,"subtopic":52,"topic":53,"topicSlug":54,"updated":55,"__hash__":56},"qa\u002Fpython\u002Ffundamentals\u002Fstrings-formatting.md","Strings Formatting",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,4,"\u002Fpython\u002Ffundamentals\u002Fstrings-formatting",[23,27,31,36,40,44],{"id":24,"difficulty":14,"q":25,"a":26},"fstring-vs-format-vs-percent","What is the difference between f-strings, .format(), and % formatting?","All three interpolate values into strings. **`%`** is the oldest C-style syntax.\n**`str.format()`** uses `{}` placeholders and is more flexible. **f-strings**\n(Python 3.6+) embed expressions **inline** and are the fastest and most readable.\n\n```python\nname, n = \"Ada\", 3\n\"Hi %s, %d items\" % (name, n)        # old % style\n\"Hi {}, {} items\".format(name, n)    # str.format\nf\"Hi {name}, {n} items\"              # f-string — preferred\nf\"{n * 2 = }\"                        # \"n * 2 = 6\"  — self-documenting\n```\n\nRule of thumb: prefer **f-strings** for new code — they evaluate expressions\ndirectly and avoid the argument-ordering errors of `%` and `.format()`.\n",{"id":28,"difficulty":14,"q":29,"a":30},"str-vs-bytes","What is the difference between str and bytes?","A **`str`** is a sequence of **Unicode code points** (text); **`bytes`** is a\nsequence of **raw bytes** (0-255). You convert between them with **`encode`**\n(str -> bytes) and **`decode`** (bytes -> str), specifying an encoding like UTF-8.\n\n```python\ns = \"café\"\nb = s.encode(\"utf-8\")    # b'caf\\xc3\\xa9'  — 5 bytes (é is 2)\nb.decode(\"utf-8\")        # \"café\"  — back to text\nlen(s), len(b)           # (4, 5)\ns + b                    # TypeError — can't mix str and bytes\n```\n\nWhy it matters: files and network sockets deal in **bytes**, your program logic in\n**str**. Rule of thumb: decode bytes to str as early as possible and encode back to\nbytes only at the I\u002FO boundary.\n",{"id":32,"difficulty":33,"q":34,"a":35},"common-string-methods","easy","What are the common string methods like split, strip, and join?","**`split`** breaks a string into a list on a separator; **`strip`** removes\nleading\u002Ftrailing whitespace (or given characters); **`join`** glues an iterable of\nstrings together with a separator. All return **new** strings since `str` is\nimmutable.\n\n```python\n\"  a,b,c  \".strip()            # \"a,b,c\"\n\"a,b,c\".split(\",\")            # [\"a\", \"b\", \"c\"]\n\",\".join([\"a\", \"b\", \"c\"])     # \"a,b,c\"\n\"Hello\".lower(), \"Hi\".upper() # (\"hello\", \"HI\")\n\"hello\".replace(\"l\", \"L\")     # \"heLLo\"\n```\n\nRule of thumb: `sep.join(list)` is the inverse of `text.split(sep)`, and chaining\nthese covers most everyday text wrangling.\n",{"id":37,"difficulty":14,"q":38,"a":39},"join-vs-concat-loop","Why use join instead of += to build a string in a loop?","Strings are **immutable**, so each `+=` creates a **brand-new string** and copies\neverything so far — turning a loop into O(n^2) work and lots of garbage. **`join`**\nallocates the result **once**, making it O(n).\n\n```python\n# Slow — new string every iteration\nresult = \"\"\nfor word in words:\n    result += word\n\n# Fast — single allocation\nresult = \"\".join(words)\n```\n\nRule of thumb: collect pieces in a list (or generator) and call `\"\".join(...)` —\nit's the Python equivalent of a `StringBuilder`.\n",{"id":41,"difficulty":33,"q":42,"a":43},"raw-strings","What is a raw string and when do you use it?","A **raw string** (`r\"...\"`) tells Python **not to process backslash escapes**, so\n`\\n`, `\\t`, etc. stay as literal backslash-plus-character. They're ideal for\n**regular expressions** and **Windows file paths**.\n\n```python\nprint(\"a\\tb\")    # a    b   — \\t is a tab\nprint(r\"a\\tb\")   # a\\tb     — backslash kept literally\n\nimport re\nre.findall(r\"\\d+\", \"x12y3\")   # ['12', '3']  — no double-backslashing\npath = r\"C:\\Users\\name\"       # backslashes stay intact\n```\n\nRule of thumb: reach for `r\"...\"` whenever your string is full of backslashes —\nit avoids the noise and bugs of escaping every one.\n",{"id":45,"difficulty":14,"q":46,"a":47},"format-spec-mini-language","How does the format spec mini-language work (padding, :.2f)?","Inside `{}` (or after `:` in `format`), a **format spec** controls alignment,\nwidth, and precision: `{value:[fill][align][width][,][.precision][type]}`. It\nworks in f-strings and `str.format` alike.\n\n```python\nf\"{42:5}\"        # \"   42\"    — width 5, right-aligned (default for numbers)\nf\"{'hi':\u003C5}|\"    # \"hi   |\"   — left-align in width 5\nf\"{'hi':^5}|\"    # \" hi  |\"   — center\nf\"{42:05}\"       # \"00042\"    — zero-padded\nf\"{3.14159:.2f}\" # \"3.14\"     — 2 decimal places\nf\"{1234567:,}\"   # \"1,234,567\"  — thousands separator\nf\"{0.25:.1%}\"    # \"25.0%\"    — percentage\n```\n\nRule of thumb: `.2f` controls decimals, a number sets width, and `\u003C`\u002F`>`\u002F`^` set\nalignment — combine them for clean tabular output.\n",null,{"description":11},"Python interview questions on f-strings vs .format vs %, str vs bytes, common string methods, join vs +=, raw strings, and the format spec mini-language.","python\u002Ffundamentals\u002Fstrings-formatting","Strings & String Formatting","Fundamentals","fundamentals","2026-06-18","Fly7brM0I0JbkO0F5-ZVq4BC9z9GcKpnaukrHV5K3lA",[58,62,65,69,70],{"subtopic":59,"path":60,"order":61},"Mutability & Data Types","\u002Fpython\u002Ffundamentals\u002Fmutability",1,{"subtopic":63,"path":64,"order":12},"Variables, Scope & the LEGB Rule","\u002Fpython\u002Ffundamentals\u002Fscope-legb",{"subtopic":66,"path":67,"order":68},"Numbers & Operators","\u002Fpython\u002Ffundamentals\u002Fnumbers-operators",3,{"subtopic":52,"path":21,"order":20},{"subtopic":71,"path":72,"order":73},"Truthiness & Type Conversion","\u002Fpython\u002Ffundamentals\u002Ftruthiness-conversion",5,1781808679301]