A string is one of the datatype in Python. String is a collection or group of characters. Strings are very important because most of the data that we handle are in the form of string. Examples of data in string format include names, age, house names, building name etc.
Creating string
String in python can be created by assigning group of characters to a variable.
They has to be enclosed in single or double quotes.
Example
str1 = 'This is Python Programming Language'
str2 = "This is Python Programming Language"
Above two lines include creation of string. In the first line, group of characters are enclosed in single quotes and assigned to a variable str1. Second line also include creation of string which is enclosed in double quotes.
There is no difference between single and double quotes while creating string. Both will have same result.
There is also an another way of creating string by enclosing group of characters into triple single or triple double quotes. These can be useful while creating string which span multiple lines.
Example
str1 = '''This is Python
Programming Language'''
str2 = """This is Python
Programming Language"""
We can use quotations to mark sub string inside a string. In this case, one type of quotes should use to mark outer string while sub string can be represented by another type of quotes.
str = 'Welcome to learning "Python" Programming language'
print(str)
Output
Welcome to learning "Python" Programming language
Same can be done in the reverse order. Now using double quotes to mark outer string and single quotes to mark inner string.
str = "Welcome to learning 'Python' Programming language"
print(str)
Output
Welcome to learning 'Python' Programming language
Escape characters can be use to format the way group of characters are displayed. \t escape character includes tabs or spaces between characters. We have used \t escape character in the below string to add some spaces before Python.
str = "Welcome to learning \tPython Programming language"
print(str)
Output
Welcome to learning Python Programming language
To disable the effects of escape characters , we can create the string as raw string by adding ‘r’ before the string.
str = r"Welcome to learning \tPython Programming language"
print(str)
Output
Welcome to learning \tPython Programming language
List of
Escape Characters | Description |
\a | Alert |
\b | Backspace |
\n | New Line |
\t | Horizontal tab space |
\v | Vertical tab space |
\r | Enter button |
\x | Character x |
\\ | Displays single \ |