1

I have the following string:

s = 'JSON, XML, XLS, XLSX, CSV, TSV'

I would like to convert it to have an "and" at the end. Is it possible to do a replace operation only at the last occurrence of something, such as:

s.replace(', ', ', and ', -1)

==>

'JSON, XML, XLS, XLSX, CSV, and TSV'
  • [This](https://stackoverflow.com/questions/19838976/grammatical-list-join-in-python) and [this](https://stackoverflow.com/questions/38981302/converting-a-list-into-comma-separated-string-with-and-before-the-last-item) should get you close – Cory Kramer Dec 18 '18 at 18:01
  • ' and'.join(s.rsplit(',',1)) – Kevin S Dec 18 '18 at 18:34

1 Answers1

0
s = 'JSON, XML, XLS, XLSX, CSV, TSV'

s_spl = s.split()
s_new = " ".join(s_spl[:-2]) + ' and ' + s_spl[-1]
print(s_new)
MalteHerrmann
  • 198
  • 1
  • 14