--- id: python-string-formatting title: "Python String Formatting" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["format() method", "index numbers", "named indexes", "파이썬 문자열 포매팅"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.9 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["python", "programming", "w3schools", "string-formatting", "f-string", "format"] raw_sources: ["https://www.w3schools.com/python/python_string_formatting.asp"] applied_in: [] github_commit: "" --- # [[Python String Formatting]] ## 🎯 한 줄 통찰 (One-line insight) f-strings can embed arbitrary Python expressions — math, if/else, even function calls — directly in `{}`, and the pre-3.6 `.format()` method supports the same modifiers plus positional/named index references for reusing one value in multiple placeholders. [S1] ## 🧠 핵심 개념 (Core concepts) - **f-string** (3.6+, preferred) — `f"..."` with `{}` placeholders for variables, operations, functions. [S1] - **Modifiers** — `:.2f` (2-decimal fixed point), `:,` (thousands separator), plus many more (`:<`/`:>`/`:^` alignment, `:+`/`:-` sign, `:b`/`:o`/`:x` base conversion, `:%` percentage, etc.). [S1] - **Operations in placeholders** — math, if/else conditionals, and even user-defined function calls can run inside `{}`. [S1] - **`.format()` method** (pre-3.6) — `"...{}...".format(value)`; still works but f-strings are faster/preferred. [S1] - **Index numbers in `.format()`** — `{0}`, `{1}` let you control placeholder order or reuse the same value multiple times. [S1] - **Named indexes in `.format()`** — `{carname}` with `txt.format(carname="Ford")`. [S1] ## 🧩 추출된 패턴 (Extracted patterns) - **Reuse a value via index** — `"His name is {1}. {1} is {0} years old.".format(age, name)` reuses `{1}` twice — something a plain positional `.format()` call can't do without repeating the argument. [S1] - **Executing arbitrary code in a placeholder** — `f"I love {fruit.upper()}"` and even calling a custom function `f"...{myconverter(30000)}..."` shows f-string placeholders aren't limited to simple variable substitution. [S1] ## 📖 세부 내용 (Details) - Conditional inside f-string: `txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"`. [S1] - Custom function inside f-string: `def myconverter(x): return x * 0.3048; txt = f"...{myconverter(30000)}..."`. [S1] - Thousands separator: `txt = f"The price is {price:,} dollars"`. [S1] - `.format()` with index numbers: `myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars.".format(quantity, itemno, price)`. [S1] - `.format()` with named indexes: `myorder = "I have a {carname}, it is a {model}.".format(carname="Ford", model="Mustang")`. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) 소스에서 모순되는 정보는 발견되지 않음. ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — Python Strings Format 챕터에서 이미 소개된 f-string 기초가 여기서 modifier 전체 목록과 format() 메서드로 확장된다. [S1] ## 💻 코드 패턴 (Code patterns) Function call and conditional inside an f-string (Python): ```python def myconverter(x): return x * 0.3048 txt = f"The plane is flying at a {myconverter(30000)} meter altitude" ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.90 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[Python Tutorial]] - **관련 개념:** [[Python Strings Format]], [[Python Output Variables]] - **참조 맥락:** Strings Format 챕터의 f-string 기초를 modifier 전체 목록과 format() 메서드로 확장. ## 📚 출처 (Sources) - [S1] W3Schools — Python String Formatting — https://www.w3schools.com/python/python_string_formatting.asp ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "Python String Formatting" page (Astra wiki-curation, P-Reinforce v3.1 format).