Python String: 3 examples to use strings in Python

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.

See an example of String

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.

See this example online


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:

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


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.

String replace

Split string method

string contains

Int to string method

String length method

String concatenation

Python Find

 

Was this article helpful?

Related Articles

Leave A Comment?