Python : Strings

 

In Python, strings are sequences of characters, enclosed within single quotes (') or double quotes ("). Strings are immutable, meaning their contents cannot be changed after creation.

Creating Strings:

# Single quotes 
str1 = 'Hello, World!' 
# Double quotes 
str2 = "Python Programming"3

Python provides many built-in methods and operations for working with strings. Here are some common operations and methods for manipulating strings:

1. Concatenation:
   Concatenation is the process of combining two or more strings into a single string. This is achieved using the `+` operator.


   str1 = 'Hello'
   str2 = 'World'
   concatenated_str = str1 + ', ' + str2
   print(concatenated_str)  # Output: Hello, World

  

2. String Length:
   You can find the length of a string (i.e., the number of characters) using the `len()` function.


   string = 'Python'
   print(len(string))  # Output: 6

 

3. Accessing Characters:
   Individual characters in a string can be accessed using indexing. Python uses zero-based indexing, so the first character has an index of 0.


   string = 'Python'
   print(string[0])   # Output: P
   print(string[-1])  # Output: n (accessing the last character using negative indexing)

 

4. Slicing:
   Slicing allows you to extract a substring from a string. It is performed using the syntax `string[start:end]`, where `start` is the starting index and `end` is the ending index (exclusive).


   string = 'Python Programming'
   print(string[0:6])   # Output: Python (slicing from index 0 to index 5)
   print(string[:6])    # Output: Python (slicing from the beginning to index 5)
   print(string[7:])    # Output: Programming (slicing from index 7 to the end)

 

5. String Methods:
   Python provides numerous built-in methods for string manipulation. Some commonly used methods include:

  •    upper(): Converts all characters in the string to uppercase.
  •    lower(): Converts all characters in the string to lowercase.
  •    replace(old, new): Replaces occurrences of the old substring with the new substring.
  •    split(sep): Splits the string into a list of substrings based on the specified separator (sep).
  •    startswith(prefix): Checks if the string starts with the specified prefix.
  •    endswith(suffix): Checks if the string ends with the specified suffix.


   string = 'Python Programming'
   print(string.upper())            # Output: PYTHON PROGRAMMING
   print(string.lower())            # Output: python programming
   print(string.replace('Python', 'Java'))  # Output: Java Programming
   print(string.split())            # Output: ['Python', 'Programming']
   print(string.startswith('Python'))  # Output: True
   print(string.endswith('Programming'))  # Output: True

 

6. String Formatting:
   Python provides different ways to format strings, including using the format() method and f-strings (formatted string literals).

  •   Using format(): Allows you to insert variable values into a string template.

 
     name = 'Alice'
     age = 30
     message = "My name is {} and I am {} years old.".format(name, age)
     print(message)  # Output: My name is Alice and I am 30 years old.

 

  • Using f-strings: Introduced in Python 3.6, f-strings allow you to embed expressions inside string literals.


     name = 'Bob'
     age = 25
     message = f"My name is {name} and I am {age} years old."
     print(message)  # Output: My name is Bob and I am 25 years old.

 

These are some of the common operations and methods for manipulating strings in Python. Strings are versatile and widely used for text processing, data manipulation, and formatting in Python programs.