I want to know how to divide only the numbers in the Python string.

Asked 2 years ago, Updated 2 years ago, 47 views

I'm coding with Python.

Hong Gil-dong 1,200,000 won, Lim Kkeok-jeong 3,000,000 won, and Jang Gil-san 6,000,000 won only the amount that appears in the string

divided by half Honggil-dong KRW 600,000, Im Kkeokjeong KRW 1,500,000, Janggil-san KRW 3,000,000 or

divided by one-third I don't know how to make it 400,000 won for Hong Gil-dong, 1,000,000 won for Lim Kkeok-jeong, and 2,000,000 won for Jang Gil-san.

In other words, the method of dividing only the amount shown in the string while freely changing the dividing ratio (keep a comma in a thousand units) I'd like to know about that.

I vaguely understand that I can use the re module, but I'm not sure.

python string regex

2022-09-20 20:47

1 Answers

Please refer to the following.

import re

moneys = ['1,200,000', '3,000,000', '6,000,000']
template = 'Hong Gil-dong {0} won, Lim Kkeok-jeong {1} won, Jang Gil-san {2} won'
print(template.format(*moneys))

m = re.compile (r'Hong Gil-dong (\d{1,3}[,\d{3}]*) circle, Im Kkeok-jeong (\d{1,3}[,\d{3}]*) circle, Jang Gil-san (\d{1,3}[,\d{3}]*) circle')
print(template.format(*['{:,}'.format(int(money.translate({ord(','): ''})) // 2) for money in m.search(s).groups()]))


1,200,000 won for Honggil-dong, 3,000,000 won for Lim Kkeokjeong, 6,000,000 won for Janggil-san
600,000 won for Honggil-dong, 1,500,000 won for Lim Kkeok-jeong, 3,000,000 won for Janggil-san


2022-09-20 20:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.