Strings in python
Strings in Python
In Python, strings are sequences of characters used to represent textual data such as names, messages, or file contents. They can include letters, numbers, spaces, and special symbols like @, %, or &.
Character Encoding
Python uses Unicode to store characters as integer values, making it capable of representing characters from many languages and symbol sets.
For instance, the ASCII subset maps:
-
'A'to'Z'→ 65 to 90 -
'a'to'z'→ 97 to 122
ord() and chr() Functions
-
ord(char)→ Returns the Unicode code of the character. -
chr(code)→ Converts a Unicode code point back to the corresponding character.
Example:
String Immutability
Strings in Python are immutable, meaning you cannot change their content after creation. Any direct attempt to modify a character will raise an error.
Example:
Creating Strings
Strings can be created using:
-
Single quotes:
'Hello' -
Double quotes:
"Hello" -
Triple quotes:
'''Hello'''or"""Hello"""(for multi-line text)
Example:
Accessing Characters in a String
You can access characters using indexing:
-
Positive index starts from the beginning (0-based).
-
Negative index starts from the end.
Example: