Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python用置换值替换字符串_Python_Python 3.x - Fatal编程技术网

Python用置换值替换字符串

Python用置换值替换字符串,python,python-3.x,Python,Python 3.x,我有一个字符串示例str1='0x23x' 排列将为排列中的i生成所有可能的数字:('123456789',2): 在排列运行之后,我希望将str1中的x替换为排列得到的数字 我们会像 01232 01233 01234 . . . 09238 如何实现这一点?您可以使用replace()将第一个x替换为置换的第一个元素,然后再次调用它以替换第二个x: from itertools import permutations str1 = '0x23x' for i in permutatio

我有一个字符串示例
str1='0x23x'
排列
将为排列中的i生成所有可能的数字:
('123456789',2):

在排列运行之后,我希望将
str1
中的
x
替换为排列得到的数字

我们会像

01232
01233
01234
.
.
.
09238
如何实现这一点?

您可以使用
replace()
将第一个x替换为置换的第一个元素,然后再次调用它以替换第二个x:

from itertools import permutations

str1 = '0x23x'

for i in permutations('123456789', 2):
    print(str1.replace("x", i[0], 1).replace("x", i[1], 1))

您可以将输入的str转换为格式字符串,只需格式化

str_format = str1.replace('x', '{}') 
for i in permutations('123456789', 2): 
  print(str_format.format(*i))
str_format = str1.replace('x', '{}') 
for i in permutations('123456789', 2): 
  print(str_format.format(*i))