Wednesday, September 4, 2024

BASICS PYTHON PROGRAMMING (Arrays and Strings)

 Arrays Using Lists:


In Python, you can create arrays using lists. Lists are dynamic arrays that can hold elements of different data types.

# Creating an array using a list
my_array = [1, 2, 3, 4, 5]

# Accessing elements in the array
print(my_array[0])  # Output: 1

You can perform various operations on lists, such as appending, extending, and slicing:

# Appending an element to the end of the array
my_array.append(6)

# Extending the array with another list
my_array.extend([7, 8, 9])

# Slicing the array to get a subset
subset = my_array[2:5]  # [3, 4, 5]


Strings:

Strings are sequences of characters and are immutable.
They are defined using single quotes '' or double quotes "".
Example:

my_string = "strings are a fundamental data type"


In Python, strings are a fundamental data type, and the language provides a wide range of built-in string methods to manipulate and work with strings effectively.

str.capitalize():

This method returns a copy of the string with its first character capitalized and the rest of the characters in lowercase

text = "strings are a fundamental data type"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: "Hello world"

str.upper() and str.lower():

str.upper() converts all characters in a string to uppercase.
str.lower() converts all characters in a string to lowercase.

text = "Hello World"
upper_text = text.upper()
lower_text = text.lower()
print(upper_text)  # Output: "HELLO WORLD"
print(lower_text)  # Output: "hello world"

str.strip([chars]):

This method returns a copy of the string with leading and trailing characters (specified in the optional chars parameter) removed.

text = "   Hello, World!   "
stripped_text = text.strip()  # Removes leading/trailing spaces
print(stripped_text)  # Output: "Hello, World!"


str.replace(old, new[, count]):

This method replaces all occurrences of the old substring with the new substring in the string. You can also specify the count parameter to limit the number of replacements.

Example:

text = "Hello, World, World"
new_text = text.replace("World", "Python")
print(new_text)  # Output: "Hello, Python, Python"

str.split([sep[, maxsplit]]):

This method splits the string into a list of substrings based on the specified separator (sep). You can also specify the maximum number of splits with the maxsplit parameter.

text = "apple,banana,orange"
fruits = text.split(",")
print(fruits)  # Output: ['apple', 'banana', 'orange']

You can split a sentence into words using the split() function in Python. By default, split() separates the string at whitespace characters (spaces, tabs, and newline characters). You can also specify a custom separator if needed. Here's how you can use the split() function:

# Splitting a sentence into words using the default separator (whitespace)
sentence = "This is a sample sentence."
words = sentence.split()

# Printing the list of words
print(words)

In the example above, the split() function splits the sentence string into a list of words using whitespace as the separator.

If you want to split a sentence using a custom separator (e.g., comma or hyphen), you can pass that separator as an argument to the split() function:

# Splitting a sentence using a custom separator (e.g., comma)
sentence = "Apples,bananas,oranges"
words = sentence.split(',')

# Printing the list of words
print(words)

In this case, we used a comma as the separator to split the sentence into words.

Remember that the split() function returns a list of words, and you can then manipulate or iterate through this list as needed for your specific task

str.join(iterable):

This method concatenates elements from an iterable (e.g., a list or tuple) using the string as a separator.
Example:

fruits = ['apple', 'banana', 'orange']
joined_text = ', '.join(fruits)
print(joined_text)  # Output: "apple, banana, orange"

str.startswith(prefix[, start[, end]]) and str.endswith(suffix[, start[, end]]):

These methods check whether a string starts or ends with the specified prefix or suffix, respectively. The optional start and end parameters can be used to specify the range of characters to check.
Example:

text = "Hello, World"
starts_with_hello = text.startswith("Hello")
ends_with_world = text.endswith("World")
print(starts_with_hello)  # Output: True
print(ends_with_world)    # Output: True

These are some of the most commonly used string methods in Python. String methods make it easy to perform a wide range of operations on strings, from simple transformations to more complex manipulations. You can combine these methods to achieve more sophisticated string processing tasks.

Common string operations include:

Concatenation: +
Slicing: my_string[0:5]
Length: len(my_string)
String methods: split(), strip(), upper(), lower(), replace(), etc.

No comments:

Post a Comment