Python – String
String in Python is a series, or sequence, of characters in order.
Strings are immutable which means once a string has been created it cannot be changed. If you try to change a string you will in fact create a new string. New String will not affect the original string in anyway.
To define the start and end of a string we have used the single quote character ‘, thus all of the following are valid strings:
'Hello' 'Hello World' 'Hello TalksInfo 2020' 'TalkInfo is improving everyday'
Initialize a String in Python
We can also define an empty string which has no characters in it (it is defined as a single quote followed immediately by a second single quote with no gap between them). This is often used to initialize or reset a variable holding a reference to a string, for example
some_string = ''
Representing a String
As stated above, we have used single quotes to define the start and end of a string, however in Python single or double quotes can be used to define a string, thus both of the following are valid:
'Hello World' "Hello World"
Illegal representation of String
You should note however, that you cannot mix the two styles of start and end strings, that is you cannot start a string with a single quote and end a string with a double quote, thus the following are both illegal in Python:
'Hello TalksInfo'' # This is illegal ''Hello TalksInfo' # So is this
Mix of quotes in String
The ability to use both ” and ‘ however, comes in useful if your string needs to contain one of the other type of string delimiters. This is because a single quote can be embedded in a string defined using double quotes and vice versa, thus we can write the following:
print("I'm in TalksInfo Website") print('TalksInfo says "hello" to everyone')
Output as below,
I'm in TalksInfo Website TalksInfo says "hello" to everyone
Multi-line String in Python
A third alternative is the use of triple quotes to support multi-line string in python as below,
message = """ Hello World """ print(z)
Output as below,
Following linked article will explain you more about What Can You Do with Strings?
In this article, we saw how to initialize a string, represent a string, legal/illegal usage of strings and multi-line strings.