Quickly learn Python strings with 3 examples

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.

See an example of String

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

Is

Python lesson”””

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.

Python strings

See this example online

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

is

string

lesson

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:

Python strings quotes

See this example online

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:

See this example online

The output:

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.

  1. String replace
  2. Split string method
  3. string contains
  4. Int to string method
  5. String length method
  6. String concatenation
  7. Python Find