Python String Operators


Various String Operators

OperatorNameDescriptionExample
+ConcatenationJoin the stringsstr1 + str2
*RepetitionReplicate the stringstr1 * n
[]SliceReturns character at index positionstr[i]
[ : ]Range SliceTo fetch substringstr[i:j]
inMembershipReturns true if sub-string is present in stringx in str
not inMembershipReturns true if sub-string is not present in stringx not in str
r/RRaw StringRaw string, to prevent escape sequence interpretation
%FormatString formatting

Description

Concatenation Operator

The + symbol is used as the concatenation operator. This operator is used to join the strings.

In [1]:
str1 = "Logical"
str2 = "Python"
str3 = str1 + " " + str2
print(str3)
Logical Python

Repetition Operator

The * symbol is used as the repetition operator. This operator is used to replicate the sting n number of times.

In [1]:
str1 = "Logical"
str2 = str1 * 5
print(str2)
LogicalLogicalLogicalLogicalLogical

Slice Operator

We use square brackets [ ] as the slice operator. It is used to fetch the character at the specified index location.

In [1]:
str = "Logical Python"
print(str[1])
o

Range Slice Operator

The colon inside square brackets [ : ] is used as the range slice operator. It is used to extract the substring from the string.

In [1]:
str = "Logical Python"
print(str[1:5])
ogic

Membership Operator

We have in and not in as the membership operators. The in operator returns true if the substring is present in the string, else it returns false and not in is the vice versa of the in operator.

In [1]:
str = "Logical Python"
print("Logical" in str)
True
In [2]:
str = "Logical Python"
print("OPerator" in str)
False

Raw String Operator

We can use r or R for the raw string. Raw string is used if we want to prevent escape sequence interpretation.

In [1]:
print(r"With raw string /n will not start new line")
With raw string /n will not start new line
In [2]:
print(R"With raw string /n will not start new line")
With raw string /n will not start new line

Format Operator

The symbol % is used as the format operator. This is used for the string formatting.

In [1]:
name = "Steve"
print("Hello %s" %name)
Hello Steve