How to modify a string in Python
chaitdwivedi
Posted on November 22, 2021
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"
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'
You could also try slicing to speed up the process
💖 💪 🙅 🚩
chaitdwivedi
Posted on November 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
programming 🚀 AdminProber v1.1: The Ultimate Admin Panel Finder Tool for Penetration Testers and Ethical Hackers
November 27, 2024