DEV Community

chaitdwivedi
chaitdwivedi

Posted on

2

How to modify a string in Python

You cannot!

Strings in Python are immutable (something that cannot be changed)

Why are Python strings immutable?

Read here

What can you do?

You can create a new modified string.

Examples

Convert all characters to upper case

original = "My String" 
new_string = original.upper() 
print(new_string)  # "MY STRING"
Enter fullscreen mode Exit fullscreen mode

Change one character

Since you can't really change the string, the solution is to convert it a mutable type like list and modify that.

original = "My String" 
original_list = list(original)
original_list[0] = 'm' 
new_string = "".join(original_list)
print(new_string)  # 'my String' 
Enter fullscreen mode Exit fullscreen mode

You could also try slicing to speed up the process

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more