String In Python
M3-R5.1 · Chapter 5: Sequence Data Types · 3 min read
Definition: A string is a Sequence of one or more characters (Letters, numbers, symbols) enclosed in single, double or triple quotation marks.
OR
A string is a sequence of characters enclosed within quotes. You can use either single ('hello') or double ("hello") quotes to define a string.
Example:
# Using single quotes
name = 'Naitik'
# Using double quotes
greeting = "Hello, world!"
# Using triple quotes for multi-line strings
message = """This is
a multi-line
string."""
Basics of String:
Ø Strings in Python are immutable, which means they cannot be changed after they are created. If you modify a string, Python creates a new one instead.
Ø Each character has its index or can be accessed using its index.
Ø String in python has two-way index for each location. (0, 1, 2, ……. In the forward direction and -1, -2, -3, …….. in the backward direction.)
Example: str=”prakash” # Total length of string is 7
The index of string in forward direction starts from 0 and in backward direction starts from -1.
The size of string is total number of characters present in the string. (If there are n characters in the string, then last index in forward direction would be n-1 and last index in backward direction would be –n.)
String are stored each character in contiguous location.
The character assignment is not supported in string because strings are immutabl
|
>>>s=’Python’ >>>type(s) |
>>>s1=”Python” >>>type(s1) |
>>>s2=”’Programming”’ >>>type(s2) |
>>>s[0] |
>>>s[3] |
|
Output: <class ‘str’> |
Output: <class ‘str’> |
Output: <class ‘str’> |
Output:’P’ |
Output: ’h’ |
|
>>> s=’aaa’ >>>id(s) |
>>> s=’bbb’ >>>id(s) |
>>>s1=”Python” >>>s1[0] |
>>>s1=”Python” >>>len(s1) |
>>>s1=”Python” >>>s1[-1] |
|
Output:43695392 |
Output: 43175296 |
Output: p |
Output: 6 |
Output: n |