Traversing A String With Python Programing - Coderz*United

Traversing A String With Python Programing

 



Traversing a String 

Iterating through the elements of a string, one character at a time is called traversing a given

string.

Concatenation of Strings 

‘+’ operator is used for concatenation of String. When used with numbers, ‘+’ performs addition

and is called the addition operators, but when used with Strings, it is called concatenation

operator since it joins or concatenates strings. 

s1="Core" 

s2="Python" 

s3=s1+s2 

print(s3) 

Out[ ]: CorePython 


Numbers and Strings cannot be combined as operands with a ‘+’ or ‘-’ operator. 

s1+4 

Traceback (most recent call last): 

File "", line 1, in s1+4 

TypeError: can only concatenate str (not "int") to str 

Replication of Strings 

‘*’ operator when used with numbers performs multiplication but when used with a string and

a number performs replication of the string ‘number’ times. 

For replication, Python creates a new String that is a number of repetitions of the input String.

The original String is not modified as strings are immutable. New strings can be created but

existing strings cannot be modified. 


In[1]: "Python" * 2 

Out[1]: 'PythonPython' 

In[2]: "Python" * "Python" 

Traceback (most recent call last): 

File "", line 1, in "Python" * "Python" 

TypeError: can't multiply sequence by non-int of type 'str' S


Indexing in Strings 

string

P

Y

T

H

O

N

+ve index

0

1

2

3

4

5

-ve index

-6

-5

-4

-3

-2

-1

The indexes of a string begin from 0 to (length-1) in forward direction (forward indexing)

and -1,-2,-3….,-length in the backward direction(backward indexing). 

Empty string: A string that has 0 characters. Just a pair of quotation marks.


In[1]: S='' 

       len(S) 

Out[2]: 0 

Length of a String 

Length of a string represents the number of characters(including spaces) in a String. len() function is used to find the length of the string. 

In[1]: s="Python" 

       len(s

Out[2]: 6