String In Python
String In Python
Strings in Python: -
“Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. “
Syntax:
In Python, strings are treated as the sequence of characters, which means that Python
doesn't support the character data-type.
A single character written as 'p' is treated as the string of length 1.
Example:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
String Operations: -
Python strings are "immutable" which means they cannot be
changed after they are created.
To create a string, put the sequence of characters inside either
single quotes, double quotes, or triple quotes and then assign it to
a variable.
Following are the some common string operations are:
1. String Concatenation
Joining of two or more strings into a single one is called
concatenation.
Python uses "+" operator for joining one or more strings.
Example:-
>>> str1='Hello'
>>> str2='World'
>>> print(str1+str2)
HelloWorld
2. Reverse a String
In Python Strings are sliceable.
Slicing a string gives you a new string from one point in the string,
backwards or forwards, to another point, by given increments.
They take slice notation or a slice object in a subscript:
string[begin:end:step]
Example:
>>> print(str[::-1])
gnirtS nohtyP
String Methods
Python has several built-in methods associated with the string
data type.
These methods let us easily modify and manipulate strings.
Example:
index(substr,start,end)
Example:
>>> print(str.upper())
>>> print(str.lower())
>>> print(str.startswith('Python'))
True
>>> print(str.startswith("Object"))
False
>>> print(str.endswith('oriented'))
True
>>> print(str.endswith('Python'))
False
>>> print(str.split())
>>> tmp='-'
>>> print(tmp.join(str))
>>> st='object'
>>> print(str.find(st))
10
>>> print(str.find(st,20))
-1
String Slicing: -
Slicing is the process of obtaining a portion (substring) of a string by
using its indices.
Given a string, we can use the following template to slice it and obtain a
substring:
string[start:end]
S = 'ABCDEFGHI'
print(S[2:7]) # C D E F G
>>> str='ABCDEFGHI'
>>> print(str[2:7])
CDEFG