-1

I'm trying to replace more than one character in a string with the replace function, but I can't figure out how to achieve this.

from itertools import permutations

comb = permutations([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 6)

f = open("code.txt", "w")

for i in comb:
    nums = str(i)
    cleared = nums.replace(',' or ' ' or '(' or ')', '')
    print(cleared)
    f.write(cleared + "\n")

That's what I've got so far. My problem is that the 'or' on line 6 doesn't work so only the commas get removed. Can anyone help?

mrfakename
  • 21
  • 1
  • 7
  • You shouldn't convert `i` to a string to begin with. Anyway, technically what you are asking has already been answered here: https://stackoverflow.com/questions/46629519/replace-multiple-characters-in-a-string-at-once or here: https://stackoverflow.com/questions/48350607/how-to-replace-set-or-group-of-characters-with-string-in-python. What is wrong with your method is explained here: https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true-how-can-i-compare-a-to-al – mkrieger1 Aug 07 '23 at 21:29

3 Answers3

4

Don't replace characters of string representations of tuple. Use str.join instead:

from itertools import permutations

comb = permutations("1234567890", 6)

with open("out.txt", "w") as f_out:
    for i in comb:
        print("".join(i), file=f_out)

The out.txt will contain:

123456
123457
123458
123459
123450
123465
123467
123468
123469
123460

...

EDIT: removed map(str, ..) Thanks @KellyBundy

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Ok thank you everybody for responding this quickly! I found another fix that uses another method but is a little bit quicker:

from itertools import permutations

comb = permutations([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 6)

f = open("code.txt", "w")

for i in comb:
    nums = str(i)
    cleared = nums.translate({ord(nums): None for nums in ',() '})
    print(cleared)
    f.write(cleared + "\n")

-1
def replace_multiple(text, to_replace=[',', ' ', '(', ')'], replace_by=''):
    for s in to_replace:
        text = text.replace(s, replace_by)
    return text

print(replace_multiple('Hello, World(!)'))

prints

'HelloWorld!'
Michael Hodel
  • 2,845
  • 1
  • 5
  • 10
  • The code is pretty self-explanatory & includes a straight-forward usage example. I don't see an issue with the answer. If this ends up getting deleted, so be it. – Michael Hodel Aug 09 '23 at 00:51
  • I would say that, first, this code is very different from op's, second, because code only answer are supposed to be downvoted to hell. – Itération 122442 Aug 09 '23 at 06:46