Strings in Python with Examples

This tutorial will focus on creating string data types and their functions, properties, and important methods and operations.

Python Strings

Python Strings are constructed by enclosing characters in single or double quotation marks. Even triple quotations are used in Python, but they are more commonly used to describe multiline texts and docstrings. Strings have methods such as split, replace, join, reverse, uppercase, lowercase and etc. in Python.

Python strings are immutable, meaning their value cannot be changed, only the reference.

x = "Python is Easy!"
x = "Python is FUN!" # this is the new value of x

If we try to modify a character in a string, an error will occur. This is because strings are immutable in Python and we would need to convert the string into a list, replace the list item, and then join the list elements back into a string.

x = 'sample'
x[0] = 'y'

print (x) # TypeError: 'str' object does not support item assignment

In order for you to test your Python code provided in this lesson, you must test the code on your code editor like PyCharm. But if you wish to run this code online, we also have an Online Compiler in Python for you to test your Python code for free.

And If you want to learn more about Python Programming Language or are just starting out, take a look at our Python Tutorial for Beginners.

String literals in Python

A string literal is where you specify the contents of a string in a program.

x = 'Sample String using a single delimiters'

String literals are strings that are assigned to variables. A string variable is a variable that points to a string in Python. And string literals may utilize single, double, or triple quotation marks as delimiters.

x = 'Single quotes'
y = "Double quotes"
z = '''Triple Quotes'''

# triple quotes string can extend multiple lines
z1 = """First Line
Second Line
Third Line"""

Accessing Characters

Python does not have a character type, to access Python String characters you have to use the substrings, these are regarded as one-character strings.

To access Python string characters, you must use substrings, which are considered to be single-character strings. Because Python does not support a character type.

To use or access substrings, we utilize square brackets [] coupled with an index or indices and square brackets. When trying to enter a character outside the index range, an IndexError is generated. And Indexes must be integers because this will result in a TypeError if we try to utilize floats or other kinds.

Example:

#Accessing substrings
var1 = 'itsourcecode'
print('var1 = ', var1)

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

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

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

#slicing 2nd to 2nd last character
print('var1[5:-2] = ', var1[1:-2])

Output:

var1 =  itsourcecode
var1[0] =  i
var1[-1] =  e
var1[1:5] =  tsou
var1[5:-2] =  tsourceco

If we attempt to access an index outside the allowed range or use numbers that are not integers, we will encounter issues.

>>> var1 = 'itsourcecode'

>>> var1[1.5]
TypeError: string indices must be integers

>>> var1[15]
IndexError: string index out of range

Updating String in Python

Updating a String in Python can be done by (re)assigning a variable to another string. The new value may be associated with its prior value or an entirely distinct string.

Example:

var1 = 'Hello World!'

print ("Updated String:", var1[:6] + 'Universe')

Output:

Updated String: Hello Universe

Different Python String Methods

The list below is the most common built-in String Methods:

  • Split
  • Replace
  • Join
  • Reverse
  • Uppercase
  • Lowercase

1. Python Strings Split

The Python Strings Split returns a list after splitting the string at the given separator.

The split() method divides a text into substrings if it detects the following separator:

Example:

names = "Prince, Grace, George"
print(names.split(","))

Output:

['Prince', ' Grace', ' George']

2. Python Strings Replace

The Python Strings Replace returns a string in which a specified value has been replaced by a specified value.

The replace() method substitutes one string for another.

Example:

names = "Prince, Grace, George"
print(names.replace("George", "John"))

Output:

Prince, Grace, John

3. Python Strings Join

The Python Strings Join method appends an iterable’s elements to the end of a string.

The join() method returns a string that is the concatenation of the strings contained in an iterable.

Example:

#Joining special symbols with string
print('_'.join('ITSOURCECODE'))

Output:

I_T_S_O_U_R_C_E_C_O_D_E

4. Python Strings Reverse

Python Strings Reverse is very tricky, you have to use two methods to do it.

You can directly pass the iterator returned by reversed() as an argument to join():

Example:

var1 ="itsourcecode"		
print(''.join(reversed(var1)))

Output:

edocecruosti

5. Python Strings Upper and Lower Case

In Python Strings Upper and Lower Case, you may also alter the case of a string to upper or lower case.

The upper() method returns a string with all letters capitalized:

Example:

var1 = "Hello Python!"
print(var1.upper())

Output:

HELLO PYTHON!

The lower() method returns the string with all letters in lowercase:

Example:

var1 = "ITSOURCECODE"
print(var1.lower())

Output:

itsourcecode

Python Escape Sequences

The sequence of characters in Python programming, consist of a backslash \ followed by the desired character.

To add illegal characters to a string, you can use an escape character backslash \ before the illegal character.

Example:

# enclosed with double quotation marks
print("She said, \"How are you?\"")
# enclosed with single quotation marks
print('I said, \"I am fine\"')

Output:

She said, "How are you?"
I said, "I am fine"

A double quotation within a string that is surrounded by double quotes is an example of an illegal character.

>>> print("She said, "How are you?"")
...
SyntaxError: invalid syntax

>>> print('I said, "I am fine"')
...
SyntaxError: invalid syntax

The table below is a list of all of Python’s supported escape characters.

Escape CharactersDescription
\newlineBackslash and newline ignored
\\Backslash
\'Single quote
\"Double quote
\aASCII Bell
\bASCII Backspace
\fASCII Formfeed
\nASCII Linefeed
\rASCII Carriage Return
\tASCII Horizontal Tab
\vASCII Vertical Tab
\oooCharacter with octal value ooo
\xHHCharacter with hexadecimal value HH
Python Escape Characters

String Special Operators

The table below is the list of String Special Operators:

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

OperatorDescriptionExample
+Concatenation – Adds values on either side of the operatora + b will give HelloPython
*Repetition – Creates new strings, concatenating multiple copies of the same stringa*2 will give HelloHello
[]Slice – Gives the character from the given indexa[1] will give e
[ : ]Range Slice – Gives the characters from the given rangea[1:4] will give ell
inMembership – Returns true if a character exists in the given stringH in a will give 1
not inMembership – Returns true if a character does not exist in the given stringM not in a will give 1
r/RRaw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.print r'\n' prints \n and print R'\n'prints \n
%Format – Performs String formattingSee at next section
String Special Operators

String Formatting Operator

The String Formatting Operator is exceptionally versatile and powerful for formatting strings. As placeholders or replacement fields, format strings contain curly braces {} that are substituted.

We can specify the order using either positional arguments or keyword arguments.

Example:

# default(implicit) order
var1 = "{}, {} and {} are my favorite fruits".format('Orange', 'Grapes', 'Coconut')
print('\n--- Default Order ---')
print(var1)

# order using positional argument
var1 = "{1}, {0} and {2} are my favorite fruits".format('Orange', 'Grapes', 'Coconut')
print('\n--- Positional Order ---')
print(var1)

# order using keyword argument
var1 = "{g}, {c} and {o} are my favorite fruits".format(o='Orange', g='Grapes', c='Coconut')
print('\n--- Keyword Order ---')
print(var1)

Output:

--- Default Order ---
Orange, Grapes and Coconut are my favorite fruits

--- Positional Order ---
Grapes, Orange and Coconut are my favorite fruits

--- Keyword Order ---
Grapes, Coconut and Orange are my favorite fruits

The format() method supports optional format parameters. The colon separates them from the field name. A string can be left-justified <, right-justified >, or centered in the given space.

Summary

In summary, you learned about the most common string methods in python, escape characters, and operators.

I hope that this tutorial helped you understand how to use Strings in Python programming. Check out our list of Python Tutorial Topics if you missed any of our previous lessons.

You are one step closer to creating stronger, more effective codes now that you are aware of what Python Strings are. In your code, start implementing all the string methods you have studied today.

In the next post, “Python Lists,” you’ll learn about the built-in functions and methods and their uses. So check it out now!


Leave a Comment