Python Strings

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

Example:
 

Output: 

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

Output:

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 (:)

Output:

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:

Error:

Updating the Entire String:

Output:

Deletion of a character:

Error:

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.

Error:

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.,

Output:

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 “\\”

Output:

The following table is a list of escape sequences supported by Python.

Backslash notationDescription
\aBell or alert
\bBackspace
\cxControl-x
\C-xControl-x
\eEscape
\fFormfeed
\M-\C-xMeta-Control-x
\nNewline
\nnnOctal notation, where n is in the range 0.7
\rCarriage return
\sSpace
\tTab
\vVertical tab
\xCharacter x
\xnnHexadecimal 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

OperatorDescriptionExample
+Concatenation - Adds valuesa=Hello
b=Python
a + b will give HelloPython
*Repetition - Adds multiple copies of the same stringa*2 will give -HelloPython
[]Slicing - To get a character from the given indexa[1] will give e
[ : ]Range Slicing - To get characters from the given rangea[1:4] will give ell
inReturns true if a character exists in the given stringH in a will give 1
not inReturns true if a character does not exist in the given stringS not in a will give 1
r/RRaw 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

Output:

String Formatting Operator

Format SymbolConversion
%ccharacter
%sstring conversion through str() prior to formatting
%isigned decimal integer
%dsigned decimal integer
%uunsigned decimal integer
%ooctal integer
%xhexadecimal integer (lowercase letters)
%Xhexadecimal integer (uppercase letters)
%eexponential notation (with lowercase 'e')
%Eexponential notation (with uppercase 'E')
%ffloating point real number
%gthe shorter of %f and %e
%Gthe shorter of %f and %E

Built-in String Methods:

The following table is a list of built-in methods to manipulate strings

MethodsDescription
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 Strings

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.

Rajkumar

Leave a Comment

Share via
Copy link
Powered by Social Snap