Sobes.tech
Junior

What do you know about strings in Python?

sobes.tech AI

Answer from AI

A string in Python is an immutable (immutable) sequence of Unicode characters.

Main properties and features:

  • Immutability: Once created, a string cannot be changed. Any operations that 'modify' a string actually create a new string.
  • Sequence: Characters in a string have an order and are accessible by index. Indexing starts at 0.
  • Concatenation: Joining strings using the + operator.
    # Example of concatenation
    s1 = "Hello"
    s2 = "World"
    s3 = s1 + " " + s2
    
  • Repetition: Repeating a string using the * operator.
    # Example of repetition
    s = "abc"
    repeated_s = s * 3 # "abcabcabc"
    
  • Slicing: Extracting substrings by indices.
    # Example of slicing
    s = "abcdefg"
    substring = s[1:4] # "bcd"
    
  • Iteration: Looping through characters in a string using a for loop.
    # Iterating through a string
    s = "Python"
    for char in s:
        print(char)
    
  • Length: Getting the length of a string using the len() function.
    # Getting string length
    s = "example"
    length = len(s) # 7
    
  • String methods: A set of built-in methods for working with strings (search, replace, formatting, case conversion, etc.).

Most commonly used methods:

Method Description
str.lower() Returns a new string in lowercase.
str.upper() Returns a new string in uppercase.
str.strip() Removes leading and trailing spaces (or specified characters).
str.split() Splits the string into a list of substrings by a delimiter.
str.replace(old, new) Replaces all occurrences of the substring old with new.
str.find(sub) Returns the lowest index where substring sub is found.
str.startswith(prefix) Checks if the string starts with the specified prefix.
str.endswith(suffix) Checks if the string ends with the specified suffix.
str.join(iterable) Joins elements of an iterable into a string.
  • String formatting: Various ways to embed variable values into strings.
    • F-strings (preferred method):
      # F-string formatting
      name = "Alice"
      age = 30
      message = f"Hello, {name}. You are {age} years old."
      
    • .format() method:
      # .format() method
      name = "Bob"
      age = 25
      message = "Hello, {}. You are {} years old.".format(name, age)
      
    • Old-style % formatting:
      # Old style (%) formatting
      name = "Charlie"
      age = 35
      message = "Hello, %s. You are %d years old." % (name, age)
      
  • Character representation: Strings can contain any Unicode characters. Escape sequences (e.g., \n for newline, \t for tab) are used to represent special characters.
  • Multiline strings: Created using triple quotes (""" or ''').
    # Multiline string
    multiline_text = """This is a
    multiline
    string."""
    
What do you know about strings in Python? — Python - sobes.tech