Various String Operators
Operator | Name | Description | Example |
---|---|---|---|
+ | Concatenation | Join the strings | str1 + str2 |
* | Repetition | Replicate the string | str1 * n |
[] | Slice | Returns character at index position | str[i] |
[ : ] | Range Slice | To fetch substring | str[i:j] |
in | Membership | Returns true if sub-string is present in string | x in str |
not in | Membership | Returns true if sub-string is not present in string | x not in str |
r/R | Raw String | Raw string, to prevent escape sequence interpretation | |
% | Format | String formatting |
Description
Concatenation Operator
The + symbol is used as the concatenation operator. This operator is used to join the strings.
str1 = "Logical"
str2 = "Python"
str3 = str1 + " " + str2
print(str3)
Repetition Operator
The * symbol is used as the repetition operator. This operator is used to replicate the sting n number of times.
str1 = "Logical"
str2 = str1 * 5
print(str2)
Slice Operator
We use square brackets [ ] as the slice operator. It is used to fetch the character at the specified index location.
str = "Logical Python"
print(str[1])
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.
str = "Logical Python"
print(str[1:5])
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.
str = "Logical Python"
print("Logical" in str)
str = "Logical Python"
print("OPerator" in str)
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.
print(r"With raw string /n will not start new line")
print(R"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.
name = "Steve"
print("Hello %s" %name)