Python Strings

String is a data type in python, which is used to handle array of characters. python strings are immutable. String is a sequence of Unicode characters that may be a combination of letters, numbers, or special symbols enclosed within single, double or even triple quotes. Python treats single quotes the same as double quotes and triple quotes.

Note: Python does not support a character type, they treat it as string.

Creating String

We can create a string by enclosing single quotes or double quotes or even triple quotes. String in single quotes cannot hold any other single quoted character in it, because the compiler will not recognize where to start and end the string. To overcome this problem, you have to use double quotes. Strings which contains double quotes should be define within triple quotes. Defining strings within triple quotes also allows creation of multiline strings.

Example:

#Using Single quotes
a = 'Neural Beast'

#Using Double quotes
b = "Neural Beast"

#Using Triple quotes
c = """Neural Beast"""

print(type(a))
print(type(b))
print(type(c))

Output:

<class 'str'>
<class 'str'>
<class 'str'>

Accessing characters

Square brackets along with index number can be used to access characters of the string. The indexing in python string starts from 0 for first element and n-1 for the last element, where n is the number of characters in the string.

Example:

a = "Neural Beast"
print(a[2])

Output:

u

String slicing

To access range of characters in a string we use slicing method, it is done using colon(:). The syntax is “str(start : end)“.

Example:

a = "Neural Beast"
print(a[0:6])

Output:

Neural

Deleting or Updating string

We cannot update or delete a character in a string. Strings are immutable, hence elements of a String cannot be changed once it has been assigned. If we try to delete or update a character in a string it will throw an error.

Example:

a = "Neural Beast"
a[0] = "R"
print(a)

Output:

Traceback (most recent call last):
  File "string1.py", line 2, in <module>
    a[0] = "R"
TypeError: 'str' object does not support item assignment

Update Entire String

We can assign a new string content in the existing variable as specified in the following example.

Example:

my_str = "Neural beast"
print(my_str)
my_str = "Hello Python"
print(my_str)

Output:

Neural beast
Hello Python

Replace string

We can replace a string with another string using replace() method.

Example:

my_str = "Hello Python"
print(my_str.replace("H", "F"))

Output:

Fello Python

Deleting the String

We can delete entire string using del keyword, but we cannot delete or remove a character in a string.

Example:

my_str = "Hello Python"
del my_str
print(my_str)

Output:

Traceback (most recent call last):
  File "string1.py", line 3, in <module>
    print(my_str)
NameError: name 'my_str' is not defined

Python Strings Operators

Python provies three types of operators. They are,

  • Basic Operator
  • Membership Operator
  • Relational Operator

Basic Operator

There are two types of basic operators in python string.

  • “+” is known as concatenation operator, it is used to join two strings.
  • “*” is known as Replication Operator, it concatenates the multiple copies of the same string.

Example:

#concatenate two strings
a = "Neural"
b = "Beast"
c = a + b
print(c)

#Replication of strings
a = "Neural Beast\n"
print(a*4)

Output:

#concatenate two strings
NeuralBeast

#Replication of strings
Neural Beast
Neural Beast
Neural Beast
Neural Beast

Membership Operator

There are two membership operators in python string. They are,

in operator:

This operator returns true if a character or the entire substring exists in the given string, otherwise it returns false.

Example:

a = "Neural Beast"
b = "Hello Python"
c = "Python"
print("N" in a)
print("Hello" in b)
print(c in b)

Output:

True
True
True

not in operator

It returns true if a character the entire substring does not exist in the given string. otherwise it returns false.

Example:

b = "Hello Python"
c = "Neural beast"
print(c not in b)

Output:

True

Relational Operator

We ca use all the comparison operators in string. The string are compared based on the ASCII value or Unicode.

Example:

a = "Hello World"
b = "Neural beast"
print(a < b)
print(a != b)

Output:

True
True

Strings Formatting

The string formatting operator is one of the most exciting feature of python. The formatting operator % is used to construct strings, replacing parts of the strings with the data stored in variables.

Example:

a = "Python"
b = "Tutorial"
print("Welcome to our %s programming %s" %(a, b))

Output:

Welcome to our Python programming Tutorial

format() method

We can also use format() method for formatting strings. It contains curly brackets as placeholders which can hold arguments.

Example:

a = "Python"
b = "Tutorial"
print("Welcome to our {0} programming {1}".format(a, b))
print("{n} {b} ".format(n = 'Neural', b = 'Beast'))

Output:

Welcome to our Python programming Tutorial
Neural Beast

String Formatting Character

Format charactersUsage
%ccharacter
%d (or)%isigned decimal integer
%sstring
%uunsigned decimal integer
%ooctal integer
%x(or)%Xhexadecimal integer(lower case x
refers a-f; upper case X refers A-F )
%e(or)%Eexponential notation
%ffloating point numbers
%g(or)%Gshort numbers in floating point
or exponential notation.

Escape Character

Escape sequence starts with a backslash and it can be interpreted differently. When you have use single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes.

Example:

# using single quotes
print('Neural Beast, " – Always deliver more than expected"')

# using double quotes
print("Neural Beast, \"– Always deliver more than expected\"")

# using triple quotes
print('''''Neural Beast, "– Always deliver more than expected"''')  

Output:

Neural Beast, " – Always deliver more than expected"
Neural Beast, "– Always deliver more than expected"
''Neural Beast, "– Always deliver more than expected"

List Escape Sequences

Escape sequencedescription
\aASCII bell
\bASCII backspace
\fASCII form feed
\nASCII linefeed
\rASCII carriage return
\tASCII horizontal tab
\vASCII vertical tab
\000Character with octal value000
\XhhCharacter with hexadecimal value HH

String Methods in Python

capitalize() method

capitalize() method will return a copy of the string with its first character as capital and others letters in lowercase.

Example:

str1 = "welcome to python tutorial"
print(str1.capitalize())
str2 = "WElCOME TO PYTHON TUTORIAL"
print(str2.capitalize())

Output:

Welcome to python tutorial
Welcome to python tutorial

swapcase() method

swapcase() method will return a copy of string by converting uppercase characters to lowercase and lowercase characters to uppercase.

Example:

str1 = "Welcome To Python Tutorial"
print(str1.swapcase())
str2 = "wElCOME tO pYTHON tUTORIAL"
print(str2.swapcase())

Output:

wELCOME tO pYTHON tUTORIAL
WeLcome To Python Tutorial

upper() method

upper() method will return a copy of string in uppercase.

Example:

str1 = "welcome to python tutorial"
print(str1.upper())

Output:

WELCOME TO PYTHON TUTORIAL

lower() method

lower() method will return a copy of string in lowercase.

Example:

str1 = "WElCOME TO PYTHON TUTORIAL"
print(str1.lower())

Output:

welcome to python tutorial

startswith() method

startswith() method will return True if the string starts with the specific value.

Syntax:

str.startswith(value, start, end)

Example:

str1 = "welcome to python tutorial"
print(str1.startswith("we"))
str2 = "Hello Python"
print(str2.startswith("ll", 2, 4))

Output:

True
True

endswith() method

endswith() method will return True if the string ends with specific value.

Output:

str1 = "welcome to python tutorial"
print(str1.endswith("al"))
str2 = "Hello Python"
print(str2.startswith("lo", 3, 5))

Output:

True
True

Other String Methods

FunctionDescription
Capitalize()converts first character to capital letter
Casefold()converts to casefolded strings
Center()pads string with specified character
Count()returns occurrences of substring in string
Encode()returns encoded string of given string
Endswith()checks if string ends with the specified suffix
Expandtabs()returns tab character with spaces
Find()returns index of substring
Format()formats the string using dictionary
Format_map()formats the string using dictionary
Index()returns index of substring
Input()reads and returns a line of string
Int()returns integer from a number or string
Isalnum()checks alphanumeric character
Isalpha()checks if all characters are alphabets
Isdecimal()checks decimal characters
Isdigit()checks digit characters
Isidentifier()checks for valid identifiers
Islower()checks if all alphabets in a string are lowercase
Isnumeric()checks numeric characters
Isprintable()checks printable characters
Isspace()checks whitespace characters
Istitle()checks for titlecased string
Isupper()returns if all characters are uppercase characters
Join()returns s concatenated string
Ljust()returns left _ justified string of given width
Lower()returns lowercased string
Lstrip()removes leading characters
Maketrans()returns a translation table
Partition()returns a tuple
Replace()replaces substring inside
Rfind()returns the highest index of substring
Rindex()returns highest index of substring
Rjust()returns right-justified string of given width
Rpartition()returns a tuple
Rsplit()splits string from right
Rstrip()removes trailing characters
Slice()creates a slice object specified by range()
Split()splits string from left
Splitlines()splits string at line boundaries
Startswith()checks if string starts with the specified string
Strip()removes both leading and trailing characters
Swapcase()swap uppercase characters to lowercase; vice versa
Title()returns a title cased string
Translate()returns mapped character string
Upper()returns uppercased string
Zfill()returns a copy of the string padded with zeros

More Reading

Post navigation

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *