Python String

By | June 16, 2019

In this tutorial, we will discuss Python string and also learn how to create and modify a string in python.

Table of Content:

  • Python String
  • Create a String
  • Access characters from a string
  • How to change or delete string
  • String Operations
  • String Methods.

Python String

A python string is an immutable collection or a sequence of characters, and these characters could be symbols, Alphabets, and digits too.

the Computer does not understand the characters and symbols it only understands binary values in the form of 0 and 1.

How to create a String

All the characters are written inside single quotes or double quotes known as a string. If you use triple quotes to represent a string it will become a multi-line docstring.

Let’s understand it with an example:

sq_string = 'string inside single quote'
dq_string = "string inside double quote"
tq_string = '''triple quoted string
or multi lined string         '''
print(sq_string)
print(dq_string)
print(tq_string)

#Output

string inside single quote
string inside double quote
triple quoted string
or multi lined string

Access characters from a string:

Like a list, each string character store in a sequence and using indexing we can retrieve any random character from a string. If a string contains 25 characters then the range of its indexing would be from 0 to 24 and if we try to access an index value more than 24 it will throw an index error.

Like a list, negative indexing can be also applied on a string where -1 index represents the last character of the string.

Let’s understand it with an example:

string = "Techgeekbuzz"
print("string value is:",string)
print("first character of string:", string[0])             #using index 0
print("the last character of the string:", string[-1])         # using negetive indexing
print("first four characters of the string:", string[0:4])      #using string slicing 0 to 4 and 4 is excluded

#Output

string value is: Techgeekbuzz
first character of string: T
the last character of the string: z
first four characters of the string: Tech

What if we use an index value out of range?

string = "Tech" #index range 0 to 3
print(string[4])  #using index value 4

#Output

IndexError: string index out of range

Change or delete a string value:

Strings are immutable which mean we cannot alter its character once it assigned. Though we can assign a new string to the same variable name, it does not mean we change the string it means that we have just changed the reference value to another string.

Let’s understand it with an example:

>>>string = " Python Programming "
>>> string[1]
'P'

>>>string[1] = 'p'      #here we try to change the charecter of the string

TypeError: 'str' object does not support item assignment

>>> string = ‘Java Programming’                #Here we assign a new data to the string
>>> string

'Java Programming’ 

To delete a string object we use del keyword.

Example

string = "Techgeekbuzz"
print(string)
del string             #here we have deleted the string name
print(string)

#Output

Techgeekbuzz
NameError: name 'string' is not defined

String Operations:

There are many operations that can be performed on a string.

1 String Concatenation

String concatenation means joining two string to form a single one. We use + operator between two strings to concatenate them.

Let’s understand it with an example:

string_1 = "tech"

string_2 = "geek"

string_3 = string_1 + string_2

print(string_3)

#Output

techgeek

use of * operator with a string

we can use * operator on a string but it should be operated between a string and an integer it will create multiple values of the string and concatenate them.

Let’s understand it with an example:

string = "Tech"
string_1 = string * 3
print(string_1)

#Output

TechTechTech

2 Iterating through a String

A string can be used as an iterator and using a for loop we can iterate through each character of a string.

Let’s understand it with an example:

string = "Hello"
for i in string:
    print(i)

#Output

H
e
l
l
o

3 Membership tests of string

In the membership test, we use in a keyword to check whether the specific character present in a given string or not and return a Boolean value (True or False).

>>>string = "Programmer"

>>> "P" in string
True

>>> "P" in string
True

>>> "k" in string
False

Built-in functions:

len(): len() function returns the total number of character present in the string

example:

>>> string = "Programmer"
>>> len(string)

10           
#Output 

String Methods

lower() = it convert each string character to lowercase

upper() = it convert each string character to uppercase

join() = it is used to join all items of a list and make a single string of it

split()=converts a string to a list.

find() = it return the index value of the character

replace() = it replace one character with another.

Let’s understand it with an example:

>>> a = "Apple"
>>> a.upper()
'APPLE'

>>> b= "BOSS"
>>> b.lower()
'boss'

>>> c ="iron is a metal"
>>> c.split()
['iron', 'is', 'a', 'metal']

>>> l = ["hello", "world"]
>>> " ".join(l)
'hello world'

>>> k = "Kotlin"
>>> k.replace("K", "C")
'Cotlin'

Python Tutorials


Introduction

Flow Control

Functions

Datatypes

File Handling

Object & Class

Additional Tutorials

 

Leave a Reply

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