Python Strings

Last Update : 01 Dec, 2022 Python, Programming

In this tutorial, you will learn about Python Strings.

A string is a sequence of characters.

Python Strings are surrounded by either double quotation marks or single quotation marks.

Both 'uxPython', and "uxPython" strings are the same.

You can use the print() function to display a String literal.

Example -:


This program produces the following result -:



How to assign a String to a variable?

You can assign a string value to a variable by doing with the variable name followed by an equal character and the string.

Example -:

var = "uxPython"


Multiline Strings in Python

You can make a multiline string by using three double quotes or three single quotes.

# multiline string using three double quotes.
var1 = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt"""

# multiline string using three single quotes.
var2 = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt'''


Accessing Characters of Python Strings

Python strings are arrays of bytes representing Unicode characters. But, there is no character data type in Python. A single character is a string with a length of 1.

You can use square brackets to access elements of the String. Also, the first character has the position 0.

Example -:

var = 'uxPython'
print('var = ', var)

#first character
print('var[0] = ', var[0])

#last character
print('var[-1] = ', var[-1])

#slicing 2nd to 5th character
print('var[1:5] = ', var[1:5])

#slicing 6th to 2nd last character
print('var[5:-2] = ', var[5:-2])

This program produces the following result -:

var =  uxPython
var[0] =  u
var[-1] =  n
var[1:5] =  xPyt
var[5:-2] =  h


You found this tutorial / article valuable? Need to show your appreciation? Here are some options:

01. Spread the word! Use following buttons to share this tutorial / article link on your favorite social media sites.

02. Follow us on Twitter, GitHub ,and Facebook.