Home > other >  Most Pythonic Way to Make List Unnumbered
Most Pythonic Way to Make List Unnumbered

Time:06-10

This is what I currently have:

  1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Bg5 Bg7 8. Bd3 O-O 9. Nge2 a6 10. a4 Nbd7 11. O-O Ne5 12. Bc2 Bg4 13. h3 Bxe2 14. Qxe2 Qc7 15. f4 Ned7 16. e5 dxe5 17. fxe5 Nh5 18. d6 Qb6 19. Nd5 Qxb2 20. Ne7 Kh8 21. Rab1 Qxe5 22. Qxe5 Nxe5 23. Rxb7 Rad8 24. Rd1 f6 25. Be3 Nd7 26. Bd3 a5 27. Bd2 Ne5 28. Be4 Rxd6 29. Nd5 f5 30. Nc3 fxe4 31. Nxe4 Rdd8 32. Rc1 Nd3 33. Rc2 Bd4 34. Kh2 Nf2

It's a numbered list of chess moves. What I want is this:

d4 Nf6 c4 c5 d5 e6 ...

The same list, but unnumbered. I'm new to Python and am wondering what would be the simplest and Pythonic way to achieve this. Maybe something with the .replace() function?

CodePudding user response:

Just remove every third element

text= "1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Bg5 Bg7 8. Bd3 O-O 9. Nge2 a6 10. a4 Nbd7 11. O-O Ne5 12. Bc2 Bg4 13. h3 Bxe2 14. Qxe2 Qc7 15. f4 Ned7 16. e5 dxe5 17. fxe5 Nh5 18. d6 Qb6 19. Nd5 Qxb2 20. Ne7  Kh8 21. Rab1 Qxe5 22. Qxe5 Nxe5 23. Rxb7 Rad8 24. Rd1 f6 25. Be3 Nd7 26. Bd3 a5 27. Bd2 Ne5 28. Be4 Rxd6 29. Nd5 f5 30. Nc3 fxe4 31. Nxe4 Rdd8 32. Rc1 Nd3 33. Rc2 Bd4  34. Kh2 Nf2"

text = text.split()    # split elements
del(text[::3])         # remove every third element
text = " ".join(text)  # join them back into a string


'd4 Nf6 c4 c5 d5 e6 Nc3 exd5 cxd5 d6 e4 g6 Bg5 Bg7 Bd3 O-O Nge2 a6 a4 Nbd7 O-O Ne5 Bc2 Bg4 h3 Bxe2 Qxe2 Qc7 f4 Ned7 e5 dxe5 fxe5 Nh5 d6 Qb6 Nd5 Qxb2 Ne7  Kh8 Rab1 Qxe5 Qxe5 Nxe5 Rxb7 Rad8 Rd1 f6 Be3 Nd7 Bd3 a5 Bd2 Ne5 Be4 Rxd6 Nd5 f5 Nc3 fxe4 Nxe4 Rdd8 Rc1 Nd3 Rc2 Bd4  Kh2 Nf2'

CodePudding user response:

We can use regex to replace the number in the list.

I took the list in a string. using regex sub, I replaced the number. Regex able to find the number which is end with dot(.).

import re

myStr = '1.d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Bg5 Bg7 8. Bd3 O-O 9. Nge2 a6 10. a4 Nbd7 11. O-O Ne5 12. Bc2 Bg4 13. h3 Bxe2 14. Qxe2 Qc7 15. f4 Ned7 16. e5 dxe5 17. fxe5 Nh5 18. d6 Qb6 19. Nd5 Qxb2 20. Ne7  Kh8 21. Rab1 Qxe5 22. Qxe5 Nxe5 23. Rxb7 Rad8 24. Rd1 f6 25. Be3 Nd7 26. Bd3 a5 27. Bd2 Ne5 28. Be4 Rxd6 29. Nd5 f5 30. Nc3 fxe4 31. Nxe4 Rdd8 32. Rc1 Nd3 33. Rc2 Bd4  34. Kh2 Nf2'


newStr = re.sub('\d \.', ' ', myStr)

print(newStr)
  • Related