Quick Reach
Strings in Python
Python Strings are the sequence of characters. Strings are enclosed in single or double quotes. That means Python will treat single or double quoted strings alike. In this chapter, you will learn how to create strings and at the bottom part you can find a few string methods links to their respective chapters.
This is how you may create a string in Python program:
a = “Phtyon”
strLesson = ‘This is strings lesson’
Triple quotes are also used to enclose strings in Python. This is used when strings are enclosed in multi-lines:
StrLesson = “””This
Is
Python lesson”””
Python string example
In this example, we will use all three ways to create string variables with the single, double and triple quotes and then print those variable values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
a= “This is simple string”
strLessonSingle = ‘This is strings lesson’
StrLessonTriple = “””This
is
string
lesson”””
print (“String in double quote:”, a)
print (“String in single quote:”, strLessonSingle)
print (“String in triple quote:”, StrLessonTriple)
|
Output of the above code will be:
String in double quote: This is simple string
String in single quote: This is strings lesson
String in triple quote: This
is
string
lesson
Using quotes within Python string
As mentioned earlier, python strings are enclosed in single or double quotes. What if your program has to display the quoted text? This is how we can do this in Python.
Python has two ways to include quotes within strings, see following example:
1
2
3
4
5
|
#One way is to use single quote to enclose string. And use quoted text in double quotes
str = ‘This is how to use quoted text within string “Quoted text in double quotes”‘
print (str)
|
The Output:
This is how to use quoted text within string “Quoted text in double quotes”
String with backslash for quoted text
The other way is to use the backslash() escape character in a string for including quoted text. This makes original meaning of double quote (“) to be suppressed. See example below:
1
2
3
4
5
|
#Using backslash to use quotes qithin strings
str = “Using backslash:”Quoted text in double quotes””
print (str)
|
Output will be:
Using backslash:”Quoted text in double quotes”
Escape characters in String of Python
Escape characters are those that are not printable. These characters can be represented by backslash notation. The escape sequences are special characters that have a special purpose. The escape characters are interpreted by single as well as double quotes.
Following are a few string escape characters with meanings:
b = Backspace
e = escape
n = new line
s = space
t = tab
String methods in Python
Following are few string methods in Python.
Leave A Comment?