- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How can we change the id of an immutable string in Python?
Strings in Python are immutable, that means that once a string is created, it can't be changed. When you create a string, and if you create same string and assign it to another variable they'll both be pointing to the same string/memory. For example,
>>> a = 'hi' >>> b = 'hi' >>> id(a) 43706848L >>> id(b) 43706848L
This reuse of string objects is called interning in Python. The same strings have the same ids. But Python is not guaranteed to intern strings. If you create strings that are either not code object constants or contain characters outside of the letters + numbers + underscore range, you'll see the id() value not being reused.
We change the id of the given string as follows. We assign it to two different identifiers. The ids of these variables when found are different. This is because the given string contains characters other than alphabets, digits, and underscore.
>>> a = 'weworks_45#@$' >>> b = 'weworks_45#@$' >>> id(a) 96226208L >>> id(b) 91720800L
- Related Articles
- How can we get an ID of the running process in Java 9?
- Python tuples are immutable then how we can add values to them?
- How can I represent immutable vectors in Python?
- Can we change operator precedence in Python?
- How can a Python subclass control what data is stored in an immutable instance?
- How can we get substring from a string in Python?
- How can we extract the numbers from an input string in Java?
- Immutable String in Java
- How can we change the name of a MySQL table?
- How can we change an improper fraction into a mixed fraction?
- What MySQL functions can we use to change the character case of a string?
- How we can come out of an infinite loop in Python?
- How can we convert a list of characters into a string in Python?
- How can we unpack a string of integers to complex numbers in Python?
- How we can break a string with multiple delimiters in Python?