0
  1. So I'm new with coding and this is a little Python script I made a minute ago and I'm not sure if it's very efficient.

  2. I'm not sure I formatted this question correctly anyway here is the script:

# Counts the number of pairs (in this case every time 
# 1,6, and a period are next to each other)

counting = 0

# The variable for the array I put all the characters of 
# text in.

array = []

# The variable which counts the amount of characters in 
# the text document

arraycounter = 0

# For loop that goes through text document and puts it in 
# my array.

for x in open("/tmp/python_001.py/Info.txt", "r").read():
    array.append(x)

# While loop that goes through the array and if statement 
# that checks if 1, 6, and a period are next to each other

while arraycounter + 2 < len(array):
    if array[arraycounter] == '1' and array[arraycounter + 1] == '6' and 
    array[arraycounter + 2] == '.': 
        counting += 1
    arraycounter += 1
        
# Prints the counting variable

print(counting)
VN'sCorner
  • 1,532
  • 1
  • 9
  • 13

2 Answers2

1

You don't need an array, you can slice the string to compare, and you can use range to iterate:

with open("/tmp/python_001.py/Info.txt", "r") as f:
    contents = f.read()

count = 0
for i in range(len(contents) - 2):
    if contents[i:i + 3] == "16.":
        count += 1

print(count)
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

Typically, we read lines of a file as:

with open("....", "r") as file:
    result = file.readlines()

If you are looking for '16.' to appear in a string, you can just write:

if '16.' in my_string
   ...

If you think '16.' appears more than once in a string (and in your original code, you count multiple occurrences), you can use find() which tells you the first occurrence of a string inside another string (or -1) if it doesn't occur. It also has a start= argument so you can skip over occurrences you've already found when looking for the next.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22