Python Strings

Strings are most commonly used datatype in python. Strings are created when you wrap letters, words, numbers or special character inside double quote or single quote. In this chapter you will learn following things:

  • Creating string
  • Indexing in string 
  • Negative indexing in string
  • Slicing in string
  • String Concatenation
  • String looping
  • String Operations

Creating a string  

A string is created by wrapping literals in double or single quote.

For example

a = "StringValue"
b = 'AnotherString'

Here we have created two string and assign them to two variables a and b respectively. 

Indexing in string

Indexing refers to accessing element in the string using list like syntax (e.g. list1[0], list1[1], list1[2], and so on..)

String elements(individual letters, number or character) can be accessed using indexing operator. Indexing in python starts form 0 i.e first element is in 0(zero) index , second in 1 , third in 2 and so on.

Example:

a = "StringValue"
print(a[0]) # prints S
print(a[1]) # prints t
print(a[2]) # prints r and so on
print(a[3])

Output:

S
t
r
i

Negative indexing in string

Negative indexing refers to accessing values in a string using negative index value (e.g. -1, -2, -3 and so on). Negative indexing starts with -1 which represents the last element in the string. -2 represents the second last, -3 third last and so on. Let’s see an example

a = "StringValue"

print(a[-1]) # prints e
print(a[-2]) # prints u and so on
print(a[-3])

Slicing in string

Slicing refers to getting sub items from a string. We use indexing with colon to achieve this. Let’s see an example.

a = "StringValue"
sub_string = a[1:4]
print(sub_string)

Output:

tri

Here a[1:4] represents sub string from 1 index (including 1st) to 3rd index(4-1=3 index). This indexing can be mathematically represented as  [a,b)  i.e. includes a but not b , everything inside b.

We can do more slicing operation like this

Example:

a = "StringValue"
sub1 = a[1:4]
print("sub1=", sub1)

sub2 = a[2:]  # means everything after 2nd index
print("sub2=", sub2)

sub3 = a[:5]  # means everything before 5th index
print("sub3=", sub3)

sub4 = a[:-5]  # everything before negative 5th index(gives String)
print("sub4=", sub4)

sub5 = a[-5:-1]  # everything in between negative 5st, and, neg. 1th index
print("sub5=", sub5)

Output:

sub1= tri
sub2= ringValue
sub3= Strin
sub4= String
sub5= Valu

String concatenation

concatenation refers to joining two string together we can use  +  operator  to concatenate two or multiple strings. For example.

a = "Wow!"
b = "Good job!"
result = a+b
print(result)

output:

Wow!Good job!

We can also use  join()  to join two string and format() and tuple to join them in print statement.

Example:

a = "Wow!"
b = "Good job!"
result = ' '.join([a,b])
print(result)
# using .format() method
print("{} {}".format(a,b))
# using tuple
print("%s %s" %(a,b)) 

Output:

Wow! Good job!
Wow! Good job!
Wow! Good job!

Looping in string

we can use loops to perform operation in individual string item.

Example

a = "Excellent!"
for item in a:
    print(item)

Output:

E
x
c
e
l
l
e
n
t
!

Python String operation Examples

String length:

We can use len() function to calculate string length

a = "Excellent!"
print(len(a))

Output:

10

Replacing another string within a sub-string. 

We can use replace() method to replace a string item

Syntax:

str.replace(old, new[, max])

here old represent the old item to be replaced, new represents the new item which will be added, and max represents the how many item from start to replace. The max option is optional. If we give max 2 then first matched 2 items will be replaced with new item but other will not be replaced.

Example:

str = "Wow! Here is mango. Here is potato. Here is tomato"
print(str.replace("Here", "This"))
print(str.replace("Here", "This", 2))

Output:

Wow! This is mango. This is potato. This is tomato
Wow! This is mango. This is potato. Here is tomato

As you can see in the second print statement last “Here” is not replaced by “This”. This is because we have passed 2 in the max option.

e
u
l

Leave a Reply

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