VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Q1. With example code explain join() and split() string method.
### `join()` Method:
The `join()` method takes all items in an iterable and joins them into one string. A string must be specified as the
separator.
**Syntax:** `'separator'.join(iterable)`
**Example:**
words = ['Python', 'is', 'fun']
sentence = ' '.join(words)
print(sentence)
**Output:**
Python is fun
**Explanation:** The list of words is joined using a space as a separator.
### `split()` Method:
The `split()` method splits a string into a list where each word is a list item. The default separator is any whitespace.
**Syntax:** `string.split(separator, maxsplit)`
**Example:**
text = 'Welcome to Python Programming'
words = text.split()
print(words)
**Output:**
['Welcome', 'to', 'Python', 'Programming']
**Explanation:** The string is split into individual words.
Q2. Explain the following string methods with example: i) join() ii) islower() iii) strip() iv) center()
**i) join():** Joins elements of an iterable into a single string with a specified separator.
**Example:**
list1 = ['apple', 'banana', 'cherry']
print(', '.join(list1))
**Output:** apple, banana, cherry
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
**ii) islower():** Returns True if all characters in a string are lowercase.
**Example:**
s = 'python'
print(s.islower())
**Output:** True
**iii) strip():** Removes leading and trailing whitespaces.
**Example:**
s = ' Hello Python '
print(s.strip())
**Output:** Hello Python
**iv) center():** Returns a centered string of specified width.
**Example:**
s = 'Python'
print(s.center(10, '*'))
**Output:** **Python**
Q3. Explain Python string handling methods with examples: split(), endswith(), ljust(), center(), lstrip()
**split():** Splits string into a list.
Example: 'one two three'.split() -> ['one', 'two', 'three']
**endswith():** Returns True if string ends with specified suffix.
Example: 'python.py'.endswith('.py') -> True
**ljust():** Left-justifies the string.
Example: 'code'.ljust(10, '-') -> 'code------'
**center():** Centers string in a field.
Example: 'text'.center(10, '*') -> '***text***'
**lstrip():** Removes leading whitespaces or characters.
Example: ' Hello'.lstrip() -> 'Hello'
Q4. Explain Python string handling methods with examples: join(), startswith(), rjust(), strip(), rstrip()
**join():** Joins a list into a string.
Example: '-'.join(['a', 'b', 'c']) -> 'a-b-c'
**startswith():** Checks if string starts with a specific value.
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Example: 'hello world'.startswith('hello') -> True
**rjust():** Right-justifies the string.
Example: 'text'.rjust(10, '*') -> '******text'
**strip():** Removes leading/trailing whitespace.
Example: ' data '.strip() -> 'data'
**rstrip():** Removes trailing whitespace.
Example: 'hello '.rstrip() -> 'hello'
Q5. Explain with examples: i) isalpha() ii) isalnum() iii) isspace()
**isalpha():** Returns True if all characters are alphabetic.
Example:
text = 'abc'
print(text.isalpha())
**Output:** True
**isalnum():** Returns True if all characters are alphanumeric (a-z, A-Z, 0-9).
Example:
text = 'abc123'
print(text.isalnum())
**Output:** True
**isspace():** Returns True if all characters are whitespace.
Example:
text = ' '
print(text.isspace())
**Output:** True
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Q6. List any six methods associated with string and explain each of them with example.
Here are six common string methods in Python with explanation and examples:
1. **lower()** - Converts all characters to lowercase.
Example:
text = 'PYTHON'
print(text.lower())
Output: python
2. **upper()** - Converts all characters to uppercase.
Example:
text = 'python'
print(text.upper())
Output: PYTHON
3. **title()** - Converts the first character of each word to uppercase.
Example:
text = 'python programming'
print(text.title())
Output: Python Programming
4. **replace()** - Replaces a substring with another.
Example:
text = 'I love Python'
print(text.replace('Python', 'Java'))
Output: I love Java
5. **find()** - Finds the first occurrence index of a substring.
Example:
text = 'programming'
print(text.find('g'))
Output: 3
6. **count()** - Counts the number of times a value appears.
Example:
text = 'banana'
print(text.count('a'))
Output: 3
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Q7. Explain the various string methods for the following operations with examples. (i) Removing whitespace
i) **Whitespace Removal Methods:**
- **strip()**: Removes whitespace from both sides.
Example:
text = ' Python '
print(text.strip())
Output: Python
- **lstrip()**: Removes whitespace from the left.
Example:
text = ' Python'
print(text.lstrip())
Output: Python
- **rstrip()**: Removes whitespace from the right.
Example:
text = 'Python '
print(text.rstrip())
Output: Python
ii) **Alignment Methods:**
- **rjust(width, fillchar)**: Right-aligns string.
Example:
print('Python'.rjust(10, '*'))
Output: ****Python
- **ljust(width, fillchar)**: Left-aligns string.
Example:
print('Python'.ljust(10, '-'))
Output: Python----
- **center(width, fillchar)**: Centers the string.
Example:
print('Python'.center(12, '='))
Output: ===Python===
Q8. Write the output of the following: i. 'Hello'.upper().islower() ii. 'Hello'.upper().lower() iii. '-'.join('There can
i. `'Hello'.upper().islower()`
- 'Hello'.upper() -> 'HELLO'
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
- 'HELLO'.islower() -> False
**Output:** False
ii. `'Hello'.upper().lower()`
- 'Hello'.upper() -> 'HELLO'
- 'HELLO'.lower() -> 'hello'
**Output:** hello
iii. `'-'.join('There can be only one'.split())`
- 'There can be only one'.split() -> ['There', 'can', 'be', 'only', 'one']
- '-'.join(...) -> 'There-can-be-only-one'
**Output:** There-can-be-only-one
Q9. Discuss different paths of file system.
There are two main types of file paths in any operating system:
1. **Absolute Path**:
- Specifies the full path from the root directory.
- Works independently from the current working directory.
- Example (Linux): /home/user/docs/file.txt
- Example (Windows): C:\Users\Admin\Documents\file.txt
2. **Relative Path**:
- Starts from the current working directory.
- Does not begin with root or drive letter.
- Example: ./docs/file.txt or ../file.txt
Python uses modules like `os` and `pathlib` to work with both types.
Q10. Explain the concept of file path. Also discuss absolute and relative file path.
**File Path** is a way to specify the location of a file in the computer system.
**Absolute Path:**
- Gives the full address of the file from the root.
- Example: C:\\Users\\Admin\\file.txt (Windows)
- Example: /home/user/file.txt (Linux)
**Relative Path:**
- Describes the location of the file relative to the current directory.
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
- Example: ../file.txt or ./subdir/file.txt
**Why it's important?**
- Helps in locating files for reading/writing operations.
- Useful in both local and web-based file systems.
**Python Usage:**
```python
import os
print(os.path.abspath("myfile.txt")) # Convert to absolute
```
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Q11. List and explain different file modes supported by Python.
Python supports various file modes for reading and writing files. The mode is specified in the open() function.
File Modes:
1. 'r' - Read (default): Opens a file for reading. File must exist.
2. 'w' - Write: Creates a new file or truncates existing one.
3. 'a' - Append: Adds content at the end of the file.
4. 'x' - Exclusive creation: Creates a new file. Error if file exists.
5. 'b' - Binary mode: Used with other modes to read/write binary.
6. 't' - Text mode (default): Reads/writes text.
7. 'r+' - Read and write: File must exist.
Examples:
f = open('example.txt', 'w')
f.write('Hello World')
f.close()
Q12. Write a Python program to read the contents of a file using read(), readline() and readlines().
Explanation:
- read() reads the entire content as a single string.
- readline() reads the next line from the file.
- readlines() reads all lines and returns a list.
Program:
f = open('sample.txt', 'r')
print("Using read():")
f.seek(0)
print(f.read())
f.seek(0)
print("\nUsing readline():")
print(f.readline())
f.seek(0)
print("\nUsing readlines():")
print(f.readlines())
f.close()
Output (Assume file has 3 lines):
Using read():
Hello
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
World
Python
Using readline():
Hello
Using readlines():
['Hello\n', 'World\n', 'Python']
Q13. Write a Python program to open a file in write mode and add contents to it.
Explanation:
Using 'w' mode will create a new file or overwrite if it already exists.
Program:
f = open('newfile.txt', 'w')
f.write('This is a new file.\n')
f.write('Python makes file handling easy.')
f.close()
Output:
Contents will be written to newfile.txt:
This is a new file.
Python makes file handling easy.
Q14. Write a Python program to open a file in append mode and add contents to it.
Explanation:
Append mode 'a' adds new content to the end of the file without overwriting existing data.
Program:
f = open('log.txt', 'a')
f.write('\nNew entry added.')
f.close()
Before Append:
Log starts here.
After Append:
Log starts here.
New entry added.
VTU - Introduction to Python Programming - Module 1
CO Mapped: CO1 - Demonstrate proficiency in handling loops and the creation of functions
Q15. Write a Python program to open a file and read its contents line by line using loop.
Explanation:
Using a loop with a file object automatically reads the file line by line.
Program:
with open('mydata.txt', 'r') as file:
for line in file:
print(line.strip())
Output:
(Assuming file contains three lines)
Line 1
Line 2
Line 3