Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Strengs Uforanderlighed | Strenge
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Datatyper i Python

bookStrengs Uforanderlighed

In Python, strings are immutable: once created, the characters they contain cannot be changed in place. Any "modification" you do actually creates a new string. This matters for correctness (no accidental in-place edits) and for performance (how you build larger strings).

No In-Place Edits

You can read characters by index, but you cannot assign to them.

123456
s = "hello" t = "H" + s[1:] # Creates a new string: "Hello" print(t) s[0] = "H" # TypeError: strings don't support item assignment
copy

Most string methods return a new string and leave the original unchanged.

12345678
# Cleaning up user input from a registration form user_name = " Alice " user_name.strip() # returns "Alice", but the variable still has spaces print(user_name) # " Alice " user_name = user_name.strip() # assign the cleaned value back print(user_name) # "Alice" → cleaned and ready to store
copy

Chaining is fine, but remember you're getting a new object each step.

123456
# Normalizing a user's chat message before saving it user_message = " hello\n" clean_message = user_message.strip().upper() print(user_message) # original remains " hello\n" print(clean_message) # "HELLO" → cleaned and ready for processing
copy

"Modifying" By Creating a New String

Use slicing, replace, or concatenation to produce a new value.

1234567
s = "data" s = s.replace("t", "T") # "daTa" print(s) s = s[:1] + "A" + s[2:] # "dATa" print(s)
copy

Efficient Building

Repeated + in large loops can be slow (many intermediate strings). A common pattern is to collect pieces and join once:

1234
# Combining message parts received from a device response_parts = ["Status:", " ", "200", "\n", "Success"] response_message = "".join(response_parts) # "Status: 200\nSuccess" print(response_message)
copy
Note
Note

You'll learn more joining/formatting patterns in the next chapter.

1. Which line attempts to modify a string in place and will raise an error?

2. What will the code output?

3. You need to assemble a long string from many small pieces. What's recommended?

question mark

Which line attempts to modify a string in place and will raise an error?

Select the correct answer

question mark

What will the code output?

Select the correct answer

question mark

You need to assemble a long string from many small pieces. What's recommended?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 4

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Suggested prompts:

Can you explain why string immutability is important in Python?

How can I efficiently modify or build large strings in Python?

What are some common mistakes to avoid when working with immutable strings?

bookStrengs Uforanderlighed

Stryg for at vise menuen

In Python, strings are immutable: once created, the characters they contain cannot be changed in place. Any "modification" you do actually creates a new string. This matters for correctness (no accidental in-place edits) and for performance (how you build larger strings).

No In-Place Edits

You can read characters by index, but you cannot assign to them.

123456
s = "hello" t = "H" + s[1:] # Creates a new string: "Hello" print(t) s[0] = "H" # TypeError: strings don't support item assignment
copy

Most string methods return a new string and leave the original unchanged.

12345678
# Cleaning up user input from a registration form user_name = " Alice " user_name.strip() # returns "Alice", but the variable still has spaces print(user_name) # " Alice " user_name = user_name.strip() # assign the cleaned value back print(user_name) # "Alice" → cleaned and ready to store
copy

Chaining is fine, but remember you're getting a new object each step.

123456
# Normalizing a user's chat message before saving it user_message = " hello\n" clean_message = user_message.strip().upper() print(user_message) # original remains " hello\n" print(clean_message) # "HELLO" → cleaned and ready for processing
copy

"Modifying" By Creating a New String

Use slicing, replace, or concatenation to produce a new value.

1234567
s = "data" s = s.replace("t", "T") # "daTa" print(s) s = s[:1] + "A" + s[2:] # "dATa" print(s)
copy

Efficient Building

Repeated + in large loops can be slow (many intermediate strings). A common pattern is to collect pieces and join once:

1234
# Combining message parts received from a device response_parts = ["Status:", " ", "200", "\n", "Success"] response_message = "".join(response_parts) # "Status: 200\nSuccess" print(response_message)
copy
Note
Note

You'll learn more joining/formatting patterns in the next chapter.

1. Which line attempts to modify a string in place and will raise an error?

2. What will the code output?

3. You need to assemble a long string from many small pieces. What's recommended?

question mark

Which line attempts to modify a string in place and will raise an error?

Select the correct answer

question mark

What will the code output?

Select the correct answer

question mark

You need to assemble a long string from many small pieces. What's recommended?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 4
some-alt