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:

print(ord("x")) # Output: 120 print(ord("X")) # Output: 88 print(chr(120)) # Output: x print(chr(88)) # Output: X

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:

text = "hello" # text[0] = "H" # TypeError: 'str' object does not support item assignment

Creating Strings

Strings can be created using:

  • Single quotes: 'Hello'

  • Double quotes: "Hello"

  • Triple quotes: '''Hello''' or """Hello""" (for multi-line text)

Example:

str1 = 'Hello, Python!' str2 = "Learning is fun!" str3 = """This is a multi-line string with "quotes" inside.""" print("Single quotes:", str1) print("Double quotes:", str2) print("Triple quotes:\n", str3)

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:

text = "python" print(text[0]) # p print(text[-1]) # n print(text[2]) # t print(text[-3]) # h

Popular Posts