Operations on Strings(Part-1)

Operations on Strings(Part-1)

2 min read

Some Operations on String are:-

  • Traversing
  • Concatenation
  • Replication
  • Slicing
  • Membership
  • Reversing

1.Traversing a String

Traversing string means travelling across the string or to access any (or all) of the elements of string one after the other. It is generally done by index value or loops.

#Individual elements can be accessed by index value.
s="Hello!"
print(s[1])
#Only integer values can be used as index as other will result in type error.For eg:-
print(s['t'])
Output:
e
Traceback (most recent call last):
    File "<stdin>",line 6, in <module>
TypeError: string indices must be integers.

Also, we can start index value from both sides, i.e. from the left or from the right. Left index values start from 0 whereas right index values start from -1.Python-Index
Here s[0] = s[-6] and so on. Each character is associated with an index value and can be accessed through it.

Iterating through String

Each character can also be accessed sequentially using for or while loop:
For Example: –

#Iterating through string using for loop
string='Python'
for i in string:
    print(i)
Output:-
P
y
t
h
o
n

2.Concatenation

Concatenation means to link (or group) things in a series or chain.
It creates a new string by joining two (or more than two) strings. The ‘+’ operator (or concatenation operator) joins strings written on either side of that operator and creates a new string.

s="Python "
t="Language"
print(s+t)
#Remember we can't add 'str' (string) and 'int' (integer) objects. Otherwise, it will throw an error.
print(1+s)
#But we can do the same by converting integer to string first.
print(str(1)+s)
Output:-
Traceback (most recent call last):
    File "<stdin>",line 6, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
1Python

Important:-

Strings are immutable in Python. It means once created they cannot be changed. Every-time we perform any operation, python doesn’t modify the string and creates a new string. To verify this we can try to change a character from the string using its index.
>>>s=”Immutable”
>>>s[2]=’c’
TypeError: ‘s’ object does not support item assignment.

Tags:
Choose your Reaction!
Leave a Comment