1. Strings are Immutable
Once a string is defined, it cannot be changed.
Traceback (most recent call last): File "/home/adda662df52071c1e472261a1249d4a1.py", line 9, in
a = 'E' TypeError: 'str' object does not support item assignment
But below code works fine.
In the second program, interpreter makes a copy of the original string and then work on it and modifies it. So the expression a = a +’for’ doesn’t change string but reassigns the variable a to the new string generated by the result and drops down the previous string.
Understand using id() function.
id() function is used to return the identity of an object.
string1 and string2 both point to same object or same location.Now if someone try to modify any one of the string results will be different.
93226944 'HelloWorld' 93326432
String1 is modified which contradict the fact that strings are immutable, but the identity before and after modification are different.It means a new object of the string1 is created after modification which confirms the fact that strings are immutable as no change was made in previous object of string1 rather a new one is created.
2. Three ways to create strings:
Strings in Python can be created using single quotes or double quotes or a triple quotes .
The single quotes and double quotes works same for the string creation.Talking about triple quotes, these are used when we have to write a string in multiple lines and printing as it is without using any escape sequence.
Geeks for Geeks a portal for geeks He said, "I'm fine." GeeksforGeeks a portal for geeks
How to print single quote or double quote on screen?
We can do that in the following two ways:
- First one is to use escape character to display the additional quote.
- The second way is by using mix quote, i.e., when we want to print single quote then using double quotes as delimiters and vice-versa.
Hi Mr Geek. He said, "Welcome to GeeksforGeeks" Hey so happy to be here Getting Geeky, "Loving it"
How to print escape character instead?
If there is a requirement of printing the escape character(\) instead,then if user mention it in a string interpreter will think of it as escape character and will not print it.In order to print the escape character user have to use escape character before ‘\’ as shown in the example.
\ is back slash
This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.