Day-2 | Data Types | Strings | String Handling Functions
Welcome to Day 2 in this article I learned data types and string built-in functions in Python with examples.
Data Types in Python
Data types are the foundation of every program. They define the kind of data a variable can hold. There are various data types, such as integers, floating-point numbers, booleans, and strings. Here, our primary focus is on strings.
1. Integers (int): Integers are whole numbers. They can be positive or negative, and there is no limit to their size. For example, x = 5
or y = -10
are integer variables.
2. Floating-Point Numbers (float): Floats represent real numbers. They include a decimal point. For example, pi = 3.14159
or price = 19.99
are float variables.
3. Strings (str): Strings are sequences of characters enclosed in single (' ') or double (" ") quotes. For example, name = "John"
or message = 'Hello, World!'
.
4. Booleans (bool): Booleans represent true or false values and are often used for making logical decisions. For example, is_true = True
or is_false = False
.
5. Lists: Lists are ordered collections of elements. They can contain items of different data types and are enclosed in square brackets. For example, fruits = ["apple", "banana", "cherry"]
.
6. Tuples: Tuples are similar to lists but are enclosed in parentheses. They are immutable, meaning their values cannot be changed once assigned. For example, coordinates = (10, 20)
.
7. Dictionaries: Dictionaries are collections of key-value pairs. They are enclosed in curly braces and are used for storing data in a structured way. For example, person = {"name": "Alice", "age": 30}
.
8. Sets: Sets are unordered collections of unique elements. They are enclosed in curly braces. For example, unique_numbers = {1, 2, 3, 4}
.
9. None: The None
type represents the absence of a value or a null value. It is often used to initialize variables before assigning them a proper value.
Type Conversion
You can convert one data type to another in Python using explicit type casting. For example, you can convert an integer to a float, or a string to an integer. Python provides functions like int()
, float()
, and str()
for type conversion.
Strings in python
Strings are sequences of characters, typically used to represent text. In most programming languages, strings are enclosed in single or double quotation marks. For example, "Hello, World!" is a string.
Strings are versatile and can be manipulated in numerous ways. Let's explore some common operations on strings:
1. Concatenation: Combining two or more strings. For example, "Hello" + " " + "World!" results in "Hello World!"
2. Length: Determining the number of characters in a string. In Python, you can use the len()
function to find the length of a string.
3. Indexing: Accessing individual characters in a string. In many programming languages, strings are zero-indexed, meaning the first character is at position 0. For example, in Python, my_string[0]
would return the first character.
4. Slicing: Extracting a portion of a string. You can slice a string using indices. For example, my_string[1:4]
would return the characters from index 1 to 3.
5. Searching: Finding substrings within a string. You can use functions like find()
or index()
to locate a specific substring.
String Handling Functions
Modern programming languages offer a plethora of built-in functions to manipulate strings. Here are some common functions used for string handling:
1. str.upper()
and `str.lower(): These functions convert a string to all uppercase or all lowercase characters, respectively.
**2. str.strip():
Removes leading and trailing whitespace from a string.
**3. str.replace(old, new):
Replaces all occurrences of the "old" substring with the "new" substring in the string.
**4. str.split(delimiter):
Splits a string into a list of substrings based on the provided delimiter.
**5. str.join(iterable):
Combines a list of strings into a single string, using the original string as a separator.
**6. str.startswith(prefix)
and str.endswith(suffix):
These functions check if a string starts with a specific prefix or ends with a given suffix.
**7. str.isdigit()
and str.isalpha():
These functions determine if a string consists of only digits or only alphabetic characters, respectively.
**8. str.find(sub)
and str.count(sub):
These functions help search for a substring or count its occurrences in a string.
Exploring Python's Built-In Functions
Python is renowned for its readability, simplicity, and versatility. One of the key features that make Python a powerful language is its extensive library of built-in functions. These functions are readily available for developers, simplifying various programming tasks. In this article, we'll explore some of the most commonly used built-in functions in Python.
1. print()
: Displaying Output
The print()
function is your go-to tool for displaying output to the console. It can take one or more arguments and print them to the screen. For example:
print("Hello, Python!")
2. len()
: Finding Length
The len()
function is used to find the length of an object, such as a string or a list. For instance:
text = "Python is amazing."
length = len(text) # Results in 18
3. input()
: User Input
input()
allows you to accept user input from the console. The function returns the entered text as a string.
name = input("Enter your name: ")
4. int()
, float()
, str()
: Type Conversion
Python provides functions to convert between different data types. For example, int("42")
converts the string "42" to an integer.
5. max()
and min()
: Finding Maximum and Minimum
These functions return the maximum and minimum values from a sequence, respectively. For example:
numbers = [5, 10, 2, 20, 8]
max_value = max(numbers) # Results in 20
min_value = min(numbers) # Results in 2
6. sum()
: Calculating Sum
The sum()
function calculates the sum of elements in a sequence, such as a list or tuple.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # Results in 15
7. abs()
: Absolute Value
abs()
returns the absolute value of a number. It's useful for finding the magnitude of a number, whether it's positive or negative.
value = -10
absolute_value = abs(value) # Results in 10
8. round()
: Rounding Numbers
You can use round()
to round a floating-point number to a specified number of decimal places.
pi = 3.14159
rounded_pi = round(pi, 2) # Results in 3.14
9. type()
: Determining Data Type
type()
helps you determine the data type of an object. For example:
value = 42
data_type = type(value) # Results in <class 'int'>
10. range()
: Generating a Range
The range()
function creates a sequence of numbers that you can use in loops, such as for
loops.
for num in range(1, 6):
print(num) # Outputs numbers from 1 to 5
Subscribe to my newsletter
Read articles from AQIB HAFEEZ directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
AQIB HAFEEZ
AQIB HAFEEZ
BS Computer Science student adept in DevOps, Linux, Git, GitHub, GitLab, CI/CD pipelines, Jenkins, Docker, Kubernetes, Ansible & AWS. Practical experience in these DevOps tools enhances my passion for streamlined workflows, automated processes, and holistic development solutions. Proficient in digital and Facebook marketing, aiming to merge technical acumen with marketing finesse.