I am trying to be able to replace the digit of the array with each index in another array referencing the original string.
it works with replacing single digits but when there are double digits it does not go through the full range and doubles up.
here's is relevant code
digit = str(input("digit"))
count = digit.count("%d")
def replacechar(string, char):
string = string.replace(char, "Ď")
return string
def charposition(string, char):
position = [] # list to store positions for each 'char' in 'string'
for n in range(len(string)):
if string[n] == char:
position.append(n)
print(string)
return position
the functions above and code below.
digit = replacechar(digit, "%d")
# replacing cxh
position_index = charposition(digit, 'Ď')
# creating index range
num_range = 0
for a in range(len(position_index)):
num_range = num_range * 10 9
print(num_range)
for i in range(num_range 1):
x = [int(d) for d in str(i)]
if (len(str(num_range))) > 1:
if len(x) == 1:
x.insert(0, 0)
#I have also tried this code which works however the same issue occurs
g = 0
for p in position_index:
z = digit.replace(digit[p], x[g].__str__())
print(z)
g =1
thanks!
sample output (single digit)
digit: test%d test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
sample output (multiple digits)
digit: test%d%d
test88
test00
test99
test11
test00
test11
test11
test11
test22
test11
test33
test11
test44
CodePudding user response:
Are you looking for something like this:
from itertools import product
string = input("string: ")
parts = string.split("%d")
num_digits = len(parts) - 1
if num_digits > 0:
for digits in product("0123456789", repeat=num_digits):
print(
"".join(
part digit for part, digit in zip(parts, digits)
) parts[-1]
)
Result for string == 'test%d'
:
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
Result for string == 'test%d%d'
:
test00
test01
test02
test03
...
test97
test98
test99
CodePudding user response:
It's really unclear what you try to do. But the best I can advice it's to look at regex library.
Find here a solution:
import re
import logging
from typing import Iterator
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def insert_digits(string_input:str)->Iterator[str]:
"""Replace a sequence of %d by numbers
Args:
string_input (str): string containing 1 series of %d
Yields:
Iterator[str]: yield a string where a series %d is replace by a series of digits with same length
"""
# Define a pattern: for this example a series of %d ( at least 1)
digit_pattern = re.compile(r"((%d) )")
# use search to find the first occurence of the pattern in the string
match_result = re.search(digit_pattern, string_input)
if match_result:
start,end=match_result.span()
string_begin, string_pattern, string_next=string_input[:start] , string_input[start:end 1], string_input[end 1:]
logging.debug(f"begin:{string_begin}({len(string_begin)}), pattern:{string_pattern}({len(string_pattern)}), next:{string_next}({len(string_next)})")
nb_digits=int(len(string_pattern)/2)
for index in range(0,10**nb_digits):
yield (f"{string_begin}{index:0{nb_digits}}{string_next}")
else:
logging.info("No match")
def main()->int:
"""Main function for this module
Returns:
[int]: 0 if program runs correctly
Note:
why a main function ?
- because you might import this module to use the insert digits function
- it avoid to have variable available in the global scope
- because some tools will import your module (like sphinx for documentation)
"""
try:
for p in insert_digits(string_input = "test%d%d"):
print(p)
return 0
except KeyboardInterrupt:
logging.warning("Execution Aborted manually.")
return 1
except Exception as err:
logging.error("An unhandled exception crashed the application!", err)
return 1
if __name__=="__main__":
exit(main())