0

I wish to update the list such as below:

a = ['1-1-1,', 'market area,', 'destination,', 'power,', 'power', '-', '2', '234567', '90']

into

b = ['1-1-1,', 'market area,', 'destination,', 'power,', 'power', '-', '223456790']

What it does is actually to find elements in the list and if the next element is also digit then combine it. After combining all then reupdate the list as above.

anonymous
  • 37
  • 1
  • 6
  • Does this answer your question? [How can I check if a string represents an int, without using try/except?](https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except) – mkrieger1 Feb 08 '21 at 18:54
  • No, sorry. The case is differnet from mine but thank you. – anonymous Feb 08 '21 at 18:59
  • What was the problem when you tried to do that? – mkrieger1 Feb 08 '21 at 19:00
  • Actually, I know we can use isdigit to find he digit in subtring of list but I dont know how to combine it then update the list. – anonymous Feb 08 '21 at 19:01
  • Ah, you should make it clearer in the question then what you do know and what you don't know. – mkrieger1 Feb 08 '21 at 19:02

1 Answers1

1

First we check if the element is digit using .isdigit(). If true add it to empty conc string, else check if any string is added to conc. If added append it to b list and empty conc string, else just add non-digit element to b list. Finally check whether conc string is empty or not. If not add it to b list.

a = ['1-1-1,', 'market area,', 'destination,', 'power,', 'power', '-', '2', '234567', '90']

b = []
conc = ""
for i in a:
    if i.isdigit():
        conc += i
    else:
        if len(conc) > 0:
            b.append(conc)
            conc = ""
        b.append(i)
# If string ends with digit, it will never perform else statement
# So need to add conc to b list after
if len(conc) > 0:
    b.append(conc)
Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13