我試圖能夠用參考原始字串的另一個陣列中的每個索引替換陣列的數字。
它適用于替換個位數,但當有兩位數時,它不會通過整個范圍并加倍。
這是相關代碼
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
上面的函式和下面的代碼。
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
謝謝!
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
uj5u.com熱心網友回復:
你在尋找這樣的東西:
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]
)
結果為string == 'test%d':
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
結果為string == 'test%d%d':
test00
test01
test02
test03
...
test97
test98
test99
uj5u.com熱心網友回復:
真的不清楚你想做什么。但我能建議的最好的方法是查看正則運算式庫。
在這里找到解決方案:
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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327036.html
上一篇:Connect-AzureAD:parsing_wstrust_response_failed:決議WS-Trust回應失敗
