142k views
3 votes
In this exercise, your function will receive 2 parameters, the name of a text file, and a list of strings. The function will write one line to the text file. The line will contain the fourth character of every string in the list. For any strings that don't have four characters, use x. Be sure to include the newline character at the end.

User Nixkuroi
by
6.4k points

1 Answer

0 votes

Answer:

# the function is defined

# it takes 2 arguments: filename and list of string

def solution(filename, listOfString):

# the file is opened in write mode

# so that we can write to it

with open(filename, 'w') as file_object:

# we loop through the entire list of string

# this looping help us know what to write to the file

for each_string in listOfString:

# if the length of the string is less than 4

# we write 'x' with a new line

if len(each_string) < 4:

file_object.write("x\\")

# else if the length of the string is greater than equals 4

# we write the fourth character

# and also add new line

else:

file_object.write(each_string[3])

file_object.write("\\")

Step-by-step explanation:

The function is written in Python. It takes two argument; filename and list of string.

It opens the file in write mode and then loop through the list of string. During the loop, we know what to write to the file.

In the length of a string is less than 4; we write 'x' else we write the fourth character in the string. The fourth character has an index of 3 because string uses zero index counting like a string. Starting from zero; 0, 1, 2, 3, 4... the fourth character has an index of 3.

User Shen
by
6.4k points