Python Strings
In this tutorial, you will learn to create, format, modify and delete Strings in Python.
What is String in Python?
In Python, Strings are a collection of one or more characters enclosed by either single quotation marks or double quotation marks. Python treats both single and double quotes as same. “str” is the built-in string class of python.
‘stm’ is same as “stm” in python.
How To Create A String in Python?
To create a string we enclose the characters inside single, double, or triple quotes. Triple quotes are generally used in Python to represent multiline strings. Learn about Multiline Strings here
# Python Program for creation of String # Creating a string with single quotes a = 'stm' print(a) # Creating a string with double quotes b = "stm" # Creating a string with triple quotes print(b) c = '''Learning Python Strings at Software Testing Material''' print(c)
Output:
stm
stm
Learning Python Strings
at Software Testing Material
How To Access Characters In A String
In Python, we can access individual characters of a string using indexing.
Index starts from 0 and it also allows negative address references for its sequences.
For example, the index of -1 refers to the last character, -2 refers to the second last character, and so on.
If you try to access an index out of the range will cause an IndexError.
If you try to pass float or other types instead of Integer as an index will cause a TypeError
#Python Program to Access string characters
a = 'LEARNPYTHON'
print('a = ', a)
#first character
print('a[0] = ', a[0])
#last character
print('a[-1] = ', a[-1])
Output:
a = LEARNPYTHON
a[0] = L
a[-1] = N
What Is String Slicing in Python?
In Python, we can access a range of characters in a string by using a method slicing with slicing operator colon (:)
a = 'LEARNPYTHON'
print('a = ', a) #slicing 2nd to 6th character print('a[1:6] = ', a[1:6]) #slicing 7th to 2nd last character print('a[6:-2] = ', a[6:-2])
Output:
a = LEARNPYTHON
a[1:6] = EARNP
a[6:-2] = YTH
How To Delete or Update A String?
In Python, once the string is assigned then the characters of the string cannot be deleted because the Strings are immutable. It’s possible to reassign different string to the same name.
We cannot delete characters from a string but we can delete the entire string using the built-in del keyword.
Update a character of a string:
# Python Program to update character of a String
a = "Hello world"
print("Initial String: ")
print(a)
# Updating a character of the String
b = 'p'
print("\nUpdating character at 2nd Index: ")
print(a)
Error:
TypeError: ‘str’ object does not support item assignment
Updating the Entire String:
# Python Program to update entire String
a = "Hello world"
print("Initial String: ")
print(a)
# Updating a String
a = "Learning Python"
print("\nUpdated String: ")
print(a)
Output:
Initial String: Hello world
Updated String: Learning Python
Deletion of a character:
# Python Program to delete characters from a String
a = "Hello world"
print("Initial String: ")
print(a)
# Deleting a character of the String
del a[2]
print("\nDeleting character at 2nd Index: ")
print(a)
Error:
TypeError: ‘str’ object doesn’t support item deletion
Deleting Entire String:
The deletion of the entire string is possible with the use of the del keyword. Further, if we try to print the string, this will produce an error because String is deleted and is unavailable to be printed.
# Python Program to delete entire String
a = "Hello world"
print("Initial String: ")
print(a) # Deleting a String with the use of del del a
print("\nDeleting entire String: ")
print(a)
Error:
NameError: name ‘a’ is not defined
Python String functions
We can perform many operations with String. It is one of the frequently used data types in Python.
Escape Characters:
In Python strings, the backslash “\” is one of the special characters. It is also called the “escape” character.
Backslash “\” is used in representing certain whitespace characters such as “\n” is a new line, “\t” is a tab, etc.,
print 'Python\tPHP'
print 'Python\nPHP'
Output:
Python PHP
Python PHP
To make a special character as an ordinary character, we have to prefix the special character with a backslash “\”.
For example,
A single quote (‘) can be escaped by keeping backslash before single quote “\'”
Double quote (“”) can be escaped by keeping backslash before double quote “\”\””
Even backslash (\) can be escaped by keeping backslash before it “\\”
print 'I\'m learning python' print "\"Python\"" print "\"\\\" is the backslash"
Output:
I'm learning python "Python" "\" is the backslash
The following table is a list of escape sequences supported by Python.
Backslash notation | Description |
---|---|
\a | Bell or alert |
\b | Backspace |
\cx | Control-x |
\C-x | Control-x |
\e | Escape |
\f | Formfeed |
\M-\C-x | Meta-Control-x |
\n | Newline |
\nnn | Octal notation, where n is in the range 0.7 |
\r | Carriage return |
\s | Space |
\t | Tab |
\v | Vertical tab |
\x | Character x |
\xnn | Hexadecimal notation, where n is in the range 0.9, a.f, or A.F |
String Special Operators
Assume string variable a holds ‘Learning’ and variable b holds ‘Python’, then
Operator | Description | Example |
---|---|---|
+ | Concatenation – Adds values | a=Hello b=Python a + b will give HelloPython |
* | Repetition – Adds multiple copies of the same string | a*2 will give -HelloPython |
[] | Slicing – To get a character from the given index | a[1] will give e |
[ : ] | Range Slicing – To get characters from the given range | a[1:4] will give ell |
in | Returns true if a character exists in the given string | H in a will give 1 |
not in | Returns true if a character does not exist in the given string | S not in a will give 1 |
r/R | Raw String suppresses the Escape characters. 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 |
% | To perform string formatting |
Concatenation of Two or More Strings
We can join 2 or more strings into a single string using + operator
# Python String Operations str1 = 'Learning' str2 ='Python' # using * operator print('str1 + str2 = ', str1 + str2) # using * operator print('str2 * 3 =', str2 * 3)
Output:
str1 + str2 = LearningPython
str2 * 3 = PythonPythonPython
String Formatting Operator
Format Symbol | Conversion |
---|---|
%c | character |
%s | string conversion through str() prior to formatting |
%i | signed decimal integer |
%d | signed decimal integer |
%u | unsigned decimal integer |
%o | octal integer |
%x | hexadecimal integer (lowercase letters) |
%X | hexadecimal integer (uppercase letters) |
%e | exponential notation (with lowercase ‘e’) |
%E | exponential notation (with uppercase ‘E’) |
%f | floating point real number |
%g | the shorter of %f and %e |
%G | the shorter of %f and %E |
Built-in String Methods:
The following table is a list of built-in methods to manipulate strings
Methods | Description |
---|---|
capitalize() | To make the first letter of a string caiptal |
center(width, fillchar) | Returns center-aligned string of length width. Padding is done using the specified fillchar (default filler is space). |
count(str, beg= 0,end=len(string)) | It counts how many times str occurs in a string or in a substring of a string when starting index beg and ending index end are given. |
find(str, beg=0 end=len(string)) | Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. |
index(str, beg=0, end=len(string)) | Same as find(), but raises an exception if str not found. |
isalnum() | Returns true if string has at least 1 character and all characters are alphanumeric |
isalpha() | Returns true if string has at least 1 character and all characters are alphabetic |
isdigit() | Returns true if string contains only digits |
islower() | Returns true if string has at least 1 lower cased character and all cased characters are in lowercase |
isnumeric() | Returns true if a unicode string contains only numeric characters |
isspace() | Returns true if string contains only whitespace characters |
istitle() | Returns true if string is properly “titlecased” |
isupper() | Returns true if string has at least one cased character and all cased characters are in uppercase |
join(seq) | Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. |
len(string) | Returns the length of the string |
ljust(width[, fillchar]) | Returns a space-padded string with the original string left-justified to a total of width columns. |
lower() | Converts all uppercase letters in string to lowercase. |
lstrip() | Removes all leading whitespace in string. |
maketrans() | Returns a translation table to be used in translate function. |
max(str) | Returns the max alphabetical character from the string str. |
min(str) | Returns the min alphabetical character from the string str. |
replace(old, new [, max]) | Replaces all occurrences of old in string with new or at most max occurrences if max given. |
rfind(str, beg=0,end=len(string)) | Search backwards in string. |
rindex( str, beg=0, end=len(string)) | Search backwards in string. |
rjust(width,[, fillchar]) | Returns a space-padded string with the original string right-justified to a total of width columns. |
rstrip() | Removes all trailing whitespace of a string. |
split(str=””, num=string.count(str)) | Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given. |
splitlines( num=string.count(‘\n’)) | Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed. |
startswith(str, beg=0,end=len(string)) | Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise. |
strip([chars]) | Performs both lstrip() and rstrip() on string. |
swapcase() | Inverts case for all letters in string. |
title() | Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase. |
translate(table, deletechars=””) | Translates string according to translation table str(256 chars), removing those in the del string. |
Also Read:
- Python Data Types
- Python Multiline Strings
- Python Join() Method with Examples
- How to Convert Python List to String (4 Ways)
- Python float() Function Explained with Examples
- Python Interview Questions