#atom
ID: PY-001
Date: [Insert Date]

Content:
In Python, a string is a sequence of characters enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are immutable, meaning once created, they cannot be changed. Python provides a rich set of methods for string manipulation.

Ways to Create Strings in Python:

  1. Using Single Quotes:

    str1 = 'Hello, World!'
    
  2. Using Double Quotes:

    str2 = "Hello, World!"
    
  3. Using Triple Quotes (for Multi-line Strings):

    str3 = '''
    This is a
    multi-line
    string.
    '''
    
  4. Using the str() Constructor:

    str4 = str(123)  # Converts the number 123 to a string
    
  5. Using f-Strings (Formatted String Literals):

    name = 'Alice'
    greeting = f'Hello, {name}!'  # "Hello, Alice!"
    

Common String Methods in Python:

  1. len(): Get the length of a string.

    text = 'Hello'
    print(len(text))  # 5
    
  2. upper() and lower(): Convert case.

    text = 'Hello'
    print(text.upper())  # "HELLO"
    print(text.lower())  # "hello"
    
  3. strip(): Remove leading and trailing whitespace.

    text = '   Hello, World!   '
    print(text.strip())  # "Hello, World!"
    
  4. replace(): Replace parts of a string.

    text = 'Hello, World!'
    print(text.replace('World', 'Alice'))  # "Hello, Alice!"
    
  5. split(): Split a string into a list based on a delimiter.

    text = 'apple,banana,cherry'
    print(text.split(','))  # ['apple', 'banana', 'cherry']
    
  6. join(): Join a list of strings into a single string.

    fruits = ['apple', 'banana', 'cherry']
    print(', '.join(fruits))  # "apple, banana, cherry"
    
  7. find() and index(): Search for substrings.

    text = 'Hello, World!'
    print(text.find('World'))  # 7
    print(text.index('World'))  # 7
    
  8. startswith() and endswith(): Check if a string starts or ends with a specific substring.

    text = 'Hello, World!'
    print(text.startswith('Hello'))  # True
    print(text.endswith('!'))  # True
    

Connections:


Connections:


Sources: