1. Strings are Immutable
Once a string is defined, it cannot be changed.
# A python program to show that string # cannot be changed a = 'Geeks' print a # output is displayed a = 'E' print a # causes error
Traceback (most recent call last): line 3, in
a = 'E' TypeError: 'str' object does not support item assignment
But below code works fine.
# A python program to show that a string # can be appended to a string. a = 'Geeks' print a # output is displayed a = a + 'for' print a # 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.
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. Example of single quote and double quote string. Now 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.
# A python program to create strings in three # different ways and concatenate them. a = 'Geeks' # string with single quotes b = "for" # string with double quotes c = '''Geeks a portal for geeks''' # string with triple quotes print a print b print c # Concatenation of strings created using # different quotes print a + b + c
Geeks for Geeks a portal for geeks 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.
print "Hi Mr Geek." # use of escape sequence print "He said, \"Welcome to GeeksforGeeks\"" print 'Hey so happy to be here' # use of mix quotes print 'Getting Geeky, "Loving it"'
Hi Mr Geek. He said, "Welcome to GeeksforGeeks" Hey so happy to be here Getting Geeky, "Loving it"
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 firstname.lastname@example.org. 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