In This Tutorial:
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 see a few string methods links to their respective chapters.
How to create strings?
This is how you may create a string:
a = “Phtyon”
strLesson = ‘This is strings lesson’
Triple quotes are also used to enclose strings. This is used when strings are enclosed in multi-lines:
StrLesson = “””This
An example of Python string
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.
a= "This is simple string"
strLessonSingle = 'This is strings lesson'
StrLessonTriple = """This
print ("String in double quote:", a)
print ("String in single quote:", strLessonSingle)
print ("String in triple quote:", StrLessonTriple)
The 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
Using quotes within strings
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.
Python has two ways to include quotes within strings as shown below:
#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"'
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:
#Using backslash to use quotes qithin strings
str = "Using backslash:\"Quoted text in double quotes\""
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 the 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 supported in Python
Following are few string methods in Python.
- String replace
- Split string method
- string contains
- Int to string method
- String length method
- String concatenation
- Python Find