'I don't know how to capitalize this string, while keeping the finding function of the code
Basically it is supposed to search a txt file for a string and capitalize it. I have gotten this far with some help from stack overflow but anything I try doesn't work.
import os, fileinput
import sys, subprocess
prompt = "> "
print("text to search for: ")
string1 = input(prompt)
with open(os.path.expanduser("/users/acarroll55277/documents/notes/new_myfile.txt"), 'r+') as f:
matches = list()
[matches.append(i) for i, line in enumerate(f.readlines()) if string1 in line.strip()]
f.write(f.replace(string1, string1.capitalize))
if len(matches) == 0: print(f"string {string1} not found")
[print(f"string {string1} found in line{i}") for i in matches]
and this is the error message I get
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'
Solution 1:[1]
you had some redundant function calls, and some errors such as not using () on capitalize and calling replace on a file object instead of on a string.
try this:
import os, fileinput
import sys, subprocess
prompt = "> "
print("text to search for: ")
string1 = input(prompt)
with open(os.path.expanduser("/users/acarroll55277/documents/notes/new_myfile.txt"), 'r+') as f:
matches = [line.replace(string1,string1.capitalize()) for line.strip() in f.readlines() if string1 in line]
f.writelines(matches)
if len(matches) == 0: print(f"string {string1} not found")
for i in matches:
print(f"string {string1} found in line{i}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
