Interesting facts about strings in Python

Interesting facts about strings in Python

Strings in Python have a wealth of intriguing properties and behaviors. Here are some interesting facts about them:

  1. Immutable: Strings in Python are immutable. Once you create a string, you cannot modify its content. Any operation that seems to modify a string will actually create a new string.

    s = "hello" s[0] = "H" # Raises a TypeError 
  2. Triple Quotes: Strings can be defined using triple single (''') or triple double (""") quotes. This is often used for multi-line strings or docstrings.

    multi_line = """This is a multi-line string.""" 
  3. String Interning: For optimization reasons, Python sometimes reuses the same string object rather than creating a new one. This is more common with short and simple strings.

    a = "hello" b = "hello" print(a is b) # True 
  4. Raw Strings: Strings prefixed with an r or R are treated as raw strings. Backslashes in raw strings are treated as literal backslashes and not as escape characters.

    raw_string = r"This is a raw string with a backslash: \." 
  5. String Multiplication: Strings can be "multiplied" by integers. This leads to the repetition of the string.

    s = "abc" * 3 # 'abcabcabc' 
  6. In-built Functions: Strings have many built-in methods like upper(), lower(), startswith(), endswith(), split(), and more.

  7. f-Strings: Introduced in Python 3.6, f-strings (formatted string literals) allow embedding expressions inside string literals. The expressions inside {} are evaluated at runtime and then formatted using the given format string.

    name = "Alice" greeting = f"Hello, {name}!" 
  8. Strings Are Sequences: Strings are sequences of characters, so they can be indexed, sliced, and iterated over.

    s = "python" first_char = s[0] # 'p' slice_string = s[1:4] # 'yth' 
  9. Escape Sequences: Strings can include escape sequences like \n (newline), \t (tab), \\ (backslash), and many others.

  10. Unicode Support: Python 3 strings are Unicode by default, meaning they can contain a wide range of characters from various languages and scripts.

    s = "����ˤ���" 
  11. Zero Cost Concatenation: In a specific scenario like joining strings in a list, Python optimizes memory allocation. Using "".join(list_of_strings) is a memory-efficient way to concatenate many strings.

  12. Negative Indexing: Strings support negative indexing. -1 refers to the last character, -2 refers to the second-last character, and so on.

    s = "hello" last_char = s[-1] # 'o' 

Strings are versatile in Python and are a fundamental part of the language. These interesting facts only scratch the surface of what's possible with strings in Python!


More Tags

syntax 2-way-object-databinding logstash-grok cross-join numeric stylesheet d3dimage word-style talkback zope

More Programming Guides

Other Guides

More Programming Examples