0

How to add commas at required positions in the given string in Python? In my case, the positions are not fixed.

Example: My requirement is to add the commas after 5th, 8th, 11th, 13th in an input string = "hello Python program"

My expected output would be: hello, Py,tho,n p,rogram

Is there any simplest way to achieve this in Python?

Actually I need to apply a comma on 590 positions in my file record and then process it.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Sekhar
  • 627
  • 4
  • 14
  • 34
  • 1
    Possible duplicate of [Insert some string into given string at given index in Python](https://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python) – Galen Dec 11 '17 at 10:46
  • Possible duplicate of [Add string in a certain position in Python](https://stackoverflow.com/questions/5254445/add-string-in-a-certain-position-in-python) – Pascal Rosin Dec 11 '17 at 10:50

3 Answers3

3

Strings are immutable in python, so if you're going to perform modifications on the string, it would be more efficient to convert the string to a list first. You can then call str.join on the string once you're done.

string = list("hello Python program") # somewhat counterintuitive a name

for i, j in enumerate([5, 8, 11, 13]):
     string.insert(i + j, ',')

print(''.join(string))
'hello, Py,tho,n ,program'
cs95
  • 379,657
  • 97
  • 704
  • 746
1
>>> string = "hello Python program"
>>> commas = [5, 8, 11, 13]

One way (probably the most efficient):

>>> ','.join(string[i:j] for i, j in zip([None] + commas, commas + [None]))
'hello, Py,tho,n ,program'

Another (for this one, commas should be a set for efficiency):

>>> ''.join(c + ',' * (i in commas) for i, c in enumerate(string, 1))
'hello, Py,tho,n ,program'

Another:

>>> a = list(string)
>>> for i in reversed(commas):
        a.insert(i, ',')
>>> ''.join(a)
'hello, Py,tho,n ,program'
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • I like your 2nd and 3rd options – cs95 Dec 11 '17 at 11:33
  • Possibly, yes, but I am a fan of aesthetics as much as performance ;-) – cs95 Dec 11 '17 at 11:35
  • @cᴏʟᴅsᴘᴇᴇᴅ Hmm, I do like it for aesthetics as well. I think it's more straight-forward than our others. Going character by character or inserting backwards or adding an enumeration counter to the indexes all seem somewhat indirect. – Stefan Pochmann Dec 11 '17 at 11:46
  • Hi, facing some issue with output now. I am reading a file with is of 2199 length and trying to place commas at required positions. in an output I am getting like below, commas are coming into next line. This is happening for few records. Ex: 000XXXXXX,062,035,00,00 <=== First line ,000C160YYYYY,086,047,00, <=== next line, Code is for line in file: string=list(line) commas=[15,18,21,23,25] for i in reversed(commas): string.insert(i, ',') result=''.join(string) outfile.write(result) – Sekhar Dec 14 '17 at 08:06
  • @Sekhar Then your lines probably include the newline character at the end and you're putting a comma behind that. – Stefan Pochmann Dec 14 '17 at 09:58
0

Use this function:

def insertc(index,s,c):
    return s[:index]+c+s[index:]
s='hello Python program'
j=0
for i in [5,8,11,13]:
    s=insertc(i+j,s,',')
    j+=1
print(s)
Ahmad
  • 906
  • 11
  • 27
  • Well it works now, but it was wrong before. Note that your answer is very similar to my answer, only more inefficient. – cs95 Dec 11 '17 at 10:59