Join Regular Classroom : Visit ClassroomTech

Programming in Python – codewindow.in

Related Topics

Python Programing

my_string = "Hello, World!"
print(len(my_string))  # Output: 13
  1. upper() and lower(): Convert the string to uppercase and lowercase, respectively.

my_string = "Hello, World!"
print(my_string.upper())  # Output: "HELLO, WORLD!"
print(my_string.lower())  # Output: "hello, world!"
  1. strip(): Removes leading and trailing whitespace characters.

my_string = "   Hello, World!   "
print(my_string.strip())  # Output: "Hello, World!"
  1. split(): Splits the string into a list of substrings based on a specified delimiter.

my_string = "apple,banana,orange"
fruits = my_string.split(',')
print(fruits)  # Output: ['apple', 'banana', 'orange']
  1. join(): Joins a list of strings into a single string using a specified delimiter.

fruits = ['apple', 'banana', 'orange']
my_string = ','.join(fruits)
print(my_string)  # Output: "apple,banana,orange"
  1. replace(): Replaces occurrences of a substring with another substring.

my_string = "Hello, World!"
new_string = my_string.replace('Hello', 'Hi')
print(new_string)  # Output: "Hi, World!"
  1. String Formatting: String formatting allows you to insert values into a string in a formatted way. Python provides several methods for string formatting:

    1. Using f-strings (formatted string literals):

name = "John"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)  # Output: "My name is John and I am 30 years old."
  1. Using the .format() method:

name = "John"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)  # Output: "My name is John and I am 30 years old."
  1. Using % operator (old-style formatting, less commonly used now):

name = "John"
age = 30
message = "My name is %s and I am %d years old." % (name, age)
print(message)  # Output: "My name is John and I am 30 years old."

String formatting allows you to create dynamic strings by inserting variables or values into predefined templates. It is essential for generating output, constructing messages, and formatting data in Python applications.

my_string = "Hello, world!"

 Python provides many built-in methods for working with strings.

 Here are some of the most commonly used string methods:

  • len(): Returns the length of a string.

  • lower(): Converts all characters in a string to lowercase.

  • upper(): Converts all characters in a string to uppercase.

  • strip(): Removes leading and trailing whitespace from a string.

  • split(): Splits a string into a list of substrings, based on a specified separator.

  • join(): Joins a list of strings into a single string, using a specified separator.

 Here’s an example of using some of these string methods:

my_string = "  Hello, World!  "
print(len(my_string))  # Output: 17
print(my_string.lower())  # Output: "  hello, world!  "
print(my_string.strip())  # Output: "Hello, World!"

String formatting is a way to insert values into a string. Python provides several ways to format strings, including using the % operator, the str.format() method, and f-strings (formatted string literals).

Here’s an example of using f-strings to format a string:

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

In this example, the variables name and age are inserted into the string using f-string syntax ({} enclosed in {}) to create a formatted string.

my_list = [1, 2, 3, "four", 5.0]

This creates a list with five items: the integers 1, 2, and 3, the string “four”, and the float 5.0. Note that items in a list are separated by commas and the entire list is enclosed in square brackets.

Now, let’s take a look at some of the methods you can use on lists in Python:

append(): Adds an item to the end of the list.

my_list.append(6)

insert(): Inserts an item at a specific position in the list.

my_list.insert(0, "zero")

remove(): Removes the first occurrence of an item from the list.

my_list.remove("four")

pop(): Removes and returns the item at a specific position in the list.

popped_item = my_list.pop(2)

index(): Returns the first position of an item in the list.

item_index = my_list.index("four")

sort(): Sorts the items in the list in ascending order.

my_list.sort()

reverse(): Reverses the order of the items in the list.

my_list.reverse()

count(): Returns the number of times an item appears in the list.

item_count = my_list.count(2)

Now let’s take a look at indexing in lists. Indexing allows you to access individual items in a list. In Python, indexing starts at 0, so the first item in a list is at index 0, the second item is at index 1, and so on. You can use square brackets to access an item at a specific index:

first_item = my_list[0]
second_item = my_list[1]

You can also use negative indexing to access items from the end of the list. The last item in a list has an index of -1, the second to last item has an index of -2, and so on:

last_item = my_list[-1]
second_to_last_item = my_list[-2]

Finally, you can use slicing to access a range of items in a list. Slicing allows you to specify a start index, an end index (exclusive), and a step size:

my_slice = my_list[1:4]  # items at index 1, 2, and 3
my_even_slice = my_list[::2]  # items at even indices (0, 2, 4)
my_reversed_slice = my_list[::-1]  # all items, in reverse order
my_dict = {"name": "John", "age": 30, "city": "New York"}

This creates a dictionary with three key-value pairs: “name” is associated with the value “John”, “age” is associated with the value 30, and “city” is associated with the value “New York”. Note that keys and values in a dictionary are separated by colons, and each key-value pair is separated by commas. The entire dictionary is enclosed in curly braces.

Now, let’s take a look at some of the methods you can use on dictionaries in Python:

keys(): Returns a list of all the keys in the dictionary.

key_list = my_dict.keys()

values(): Returns a list of all the values in the dictionary.

value_list = my_dict.values()

items(): Returns a list of all the key-value pairs in the dictionary as tuples.

item_list = my_dict.items()

get(): Returns the value associated with a specific key. If the key is not found, it returns a default value (which can be specified as an optional argument).

name_value = my_dict.get("name")
age_value = my_dict.get("age", 0)  # default value of 0

pop(): Removes and returns the value associated with a specific key.

city_value = my_dict.pop("city")

clear(): Removes all the key-value pairs from the dictionary.

my_dict.clear()

Now let’s take a look at how to access dictionary values. You can use square brackets and the key name to access the value associated with a specific key:

name_value = my_dict["name"]
age_value = my_dict["age"]

If the key is not found in the dictionary, a KeyError will be raised. You can also use the get() method to access dictionary values, as shown above.

You can also modify the values associated with keys in a dictionary by assigning a new value to the key:

my_dict["name"] = "Jane"
my_dict["age"] += 1

This changes the value associated with the “name” key to “Jane”, and increments the value associated with the “age” key by 1.

my_set = {1, 2, 3, 4, 5}

This creates a set with five elements: 1, 2, 3, 4, and 5. Note that the elements in a set are enclosed in curly braces, separated by commas.

Now, let’s take a look at some of the methods you can use on sets in Python:

  • add(): Adds an element to the set.

my_set.add(6)

remove(): Removes an element from the set. If the element is not found in the set, a KeyError will be raised.

my_set.remove(2)

discard(): Removes an element from the set. If the element is not found in the set, no error is raised.

my_set.discard(2)

clear(): Removes all elements from the set.

my_set.clear()

copy(): Returns a copy of the set.

new_set = my_set.copy()

pop(): Removes and returns an arbitrary element from the set. If the set is empty, a KeyError will be raised.

x = my_set.pop()

Now let’s take a look at some set operations that you can perform in Python:

  • Union: Returns a set containing all the elements from two or more sets, without any duplicates.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.union(set2)

This creates a set with the elements 1, 2, 3, and 4.

  • Intersection: Returns a set containing only the elements that are common to two or more sets.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.intersection(set2)

This creates a set with the elements 2 and 3.

  • Difference: Returns a set containing only the elements that are in one set but not in another.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.difference(set2)

This creates a set with the element 1.

  • Symmetric Difference: Returns a set containing only the elements that are in either of two sets, but not in both.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.symmetric_difference(set2)

This creates a set with the elements 1 and 4.

my_tuple = (1, 2, 3)

Tuple elements can be accessed by their index, just like with lists:

print(my_tuple[0]) # Output: 1

Tuple methods:

Although tuples are immutable, there are still some methods that you can use with tuples. Here are some examples:

  1. count() – returns the number of times a specified value appears in the tuple.

my_tuple = (1, 2, 2, 3, 4, 4, 4, 5)
print(my_tuple.count(4)) # Output: 3
  1. index() – searches the tuple for a specified value and returns the index of its first occurrence.

my_tuple = (1, 2, 2, 3, 4, 4, 4, 5)
print(my_tuple.index(3)) # Output: 3
  1. Tuple unpacking:

    Tuple unpacking allows you to assign each element of a tuple to a separate variable. Here is an example:

my_tuple = ("John", "Doe", 30)
first_name, last_name, age = my_tuple
print(first_name) # Output: John
print(last_name) # Output: Doe
print(age) # Output: 30

Tuple unpacking can also be used to swap the values of two variables without the need for a temporary variable:

x = 1
y = 2
x, y = y, x
print(x) # Output: 2
print(y) # Output: 1
x = 5
print(type(x)) # Output: <class 'int'>

In this example, we use the type() function to get the type of the x variable, which is an integer (int).

The type() function can be used to check the type of any object in Python, including variables, lists, dictionaries, functions, classes, and more.

The role of the type() function is to provide information about the type of an object, which can be useful in many situations. For example, you may want to check the type of a variable before performing a specific operation on it, or you may want to ensure that a function is only called with arguments of a certain type.

Here’s an example of how the type() function can be used to ensure that a function is only called with arguments of a specific type:

def add_numbers(x, y):
    if type(x) != int or type(y) != int:
        raise TypeError("Both arguments must be integers")
    return x + y

result = add_numbers(5, "10")
print(result) # Output: TypeError: Both arguments must be integers

In this example, we define a function called add_numbers() that takes two arguments, x and y. Before performing the addition operation, we check the types of both arguments using the type() function. If either argument is not an integer, we raise a TypeError with a specific error message.

def print_message(message):
    if message is not None:
        print(message)
    else:
        print("No message to display.")

print_message("Hello, world!") # Output: Hello, world!
print_message(None) # Output: No message to display.

In this example, we define a function called print_message() that takes a single parameter, message. Inside the function, we check whether message is None using the is operator. If message is not None, we print it to the console. If message is None, we print a default message instead.

None can also be used as a placeholder value in certain situations, such as when initializing a variable that will be assigned a value later:

my_variable = None

# Some code that may or may not assign a value to my_variable

if my_variable is not None:
    # Do something with my_variable
else:
    # Handle the case where my_variable has no value assigned to it

In this example, we initialize the my_variable variable with the value None. Later in the code, we check whether my_variable has a value assigned to it using the is not None comparison. If my_variable has a value, we perform some operation with it. If my_variable is still None, we handle this case separately.

Overall, None is a useful constant in Python that can be used to indicate the absence of a value, as well as to initialize variables or parameters that will be assigned a value later.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories