Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

chaitdwivedi
chaitdwivedi

Posted on

     

How to modify a string in Python

You cannot!

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

Why are Python strings immutable?

Readhere

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 modeExit fullscreen mode

Change one character

Since you can't really change the string, the solution is to convert it a mutable type likelist 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 modeExit fullscreen mode

You could also try slicing to speed up the process

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Writing Software for Hardware Engineers!
  • Location
    Austin, Texas
  • Education
    M.S. Computer Engineering
  • Joined

More fromchaitdwivedi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp