Python string is an object, not an array of char?

nara_lee·2025년 4월 9일
1
post-thumbnail

✅ Python string is a string object, not a raw array of characters.


🔹 What does that mean?

In Python:

s = "hello"
  • s is a str object (an instance of the built-in str class).
  • Internally, it stores a sequence of Unicode characters, not individual bytes or chars like in C.
  • You can index and iterate over it like a list or array, but:
    • You cannot modify it (it's immutable).
    • It comes with a ton of built-in methods: s.upper(), s.replace(), s.find(), etc.

🔹 Comparison to arrays of chars in other languages

FeaturePython strC/C++ char[] / Java char[]
Typestr objectRaw character array
Mutable?❌ Immutable✅ Mutable in C/C++, sometimes in Java
Unicode support✅ Built-in❌ Needs special handling
Built-in methods✅ Tons of methods (.upper())❌ Manual function writing needed
Indexable✅ Yes✅ Yes

🔹 So while this works:

s = "cat"
print(s[1])     # 'a'

This doesn't:

s[1] = 'o'      # ❌ TypeError: 'str' object does not support item assignment

If you want to modify a string, you have to create a new one:

s = "cat"
s = s[:1] + 'o' + s[2:]
print(s)        # 'cot'

TL;DR

  • ✅ Python strings are objects, not primitive arrays.
  • ✅ They behave like immutable sequences.
  • ✅ Under the hood: they're optimized, Unicode-safe, and super flexible.
  • ❌ They are not arrays of characters like in C/C++.

🔹 What is an f-string in Python?

An f-string (short for "formatted string literal") is a way to embed expressions inside string literals using curly braces {}.

✅ Syntax:

name = "Nara"
age = 25
greeting = f"Hello, my name is {name} and I’m {age} years old."
print(greeting)
# Output: Hello, my name is Nara and I’m 25 years old.

🔍 How it works:

  • The f before the string tells Python to evaluate any expressions inside {} and insert the result directly into the string.
  • You can do more than just variables — you can run expressions too:
f"The sum of 2 and 3 is {2 + 3}"  # "The sum of 2 and 3 is 5"

🔹 How is an f-string different from a regular string?

FeatureRegular Stringf-String
Syntax"Hello"f"Hello {name}"
Expression EvaluationNot supportedSupported inside {}
ConvenienceManual string formatting neededVery concise & readable

Example comparison:

# Regular string with .format()
name = "Nara"
msg = "Hello, {}!".format(name)

# f-string version
msg = f"Hello, {name}!"  # cleaner and more readable

Perfect! Now that you’ve got the concept of Python strings as full-blown objects, let’s look under the hood at how f-strings work.


🔹 What really happens when you use an f-string?

When you write:

name = "Nara"
msg = f"Hello, {name.upper()}!"

Python evaluates everything inside the {} at runtime and converts it to a string using str() (unless you override it).

Internally, f-strings are just syntactic sugar for:

msg = "Hello, " + str(name.upper()) + "!"

So, f-strings:

  • Parse the string at compile time
  • Evaluate expressions at runtime
  • Call str() on results by default (you can override that with format specs)

🔧 How Python compiles f-strings (under the hood)

Let’s take a peek using the dis module (Python's disassembler):

import dis

def greet(name):
    return f"Hello, {name}!"

dis.dis(greet)

Output (simplified):

  3           0 LOAD_CONST               1 ('Hello, ')
              2 LOAD_FAST                0 (name)
              4 FORMAT_VALUE             0
              6 BUILD_STRING             2
              8 RETURN_VALUE

Key opcodes:

  • LOAD_CONST 'Hello, ' → loads the literal part
  • LOAD_FAST name → gets the variable
  • FORMAT_VALUE → evaluates and formats the expression
  • BUILD_STRING → joins the parts together

So under the hood, f-strings are compiled into bytecode instructions that:
1. Evaluate expressions in {}
2. Convert them with str() (or repr() or format(), if you specify)
3. Concatenate them with the literal parts


🔍 f-String vs Other Formatting

Here’s how different methods behave:

name = "Nara"
age = 25
MethodCodeInternally does
f-stringf"{name} is {age}"Compile-time template + str()
.format()"{} is {}".format(name, age)Run-time lookup and string building
% formatting"%s is %d" % (name, age)Old-school C-style formatting

f-strings are faster because:

  • The template is parsed only once at compile time.
  • They avoid runtime lookup of format strings.

⚙️ Advanced use: f-string formatting

pi = 3.14159
f"Pi is {pi:.2f}"     # Pi is 3.14
f"{name:>10}"          # Right-align name in a field of 10 chars
  • You can use format specifiers like .2f, >10, etc.
  • Under the hood, Python passes those to the __format__() method of the object.

🧠 Summary

  • f"..." lets you embed variables/expressions in strings.
  • ✅ It's cleaner than "{}".format(...) or string concatenation.
  • ✅ f-strings are compiled string templates that embed dynamic expressions.
  • ✅ At runtime, they evaluate expressions inside {} and apply str().
  • ⚡ They’re faster and cleaner than .format() or %.
  • 🔍 Internally handled with bytecode instructions like FORMAT_VALUE and BUILD_STRING.

본 후기는 [한글과컴퓨터x한국생산성본부x스나이퍼팩토리] 한컴 AI 아카데미 (B-log) 리뷰로 작성 되었습니다.

#한컴AI아카데미 #AI개발자 #AI개발자교육 #한글과컴퓨터 #한국생산성본부 #스나이퍼팩토리 #부트캠프 #AI전문가양성 #개발자교육 #개발자취업

2개의 댓글

comment-user-thumbnail
2025년 4월 11일

i don't know english

1개의 답글