-5

How can I concatenate a word within the string at a particular index using Python?
For example:- In the string,

"Delhi is the capital of India." 

I need to concatenate '123' before and after 'the'.

The output should be:- "Delhi is 123the123 capital of India."

artomason
  • 3,625
  • 5
  • 20
  • 43
  • 2
    That’s insertion, not concatenation. – Davis Herring Oct 06 '18 at 14:20
  • `str.replace(' the ', ' 123the123 ')`. – Austin Oct 06 '18 at 14:23
  • This is not really concatenation, it is more like string manipulation. As @Austin suggested, you can simply replace the in the string using `str.replace()`. We also do not know the scope in which you plan on using this. If you have different strings that have multiple reoccurrences of the word "the" then this particular example would not work for you. Please clarify a bit more on how you plan on using this. – artomason Oct 06 '18 at 14:31
  • 1
    strings are immutable in python, you only ever can create new strings, f.e. by usint string methods like `replace` or by slicing - see [slice strings](https://stackoverflow.com/questions/1010961/ways-to-slice-a-string) – Patrick Artner Oct 06 '18 at 14:40
  • Thank You everybody for all the information. – Susmita Dutta Oct 07 '18 at 01:58

1 Answers1

1

You could use str.replace() or .split() and enumerate() to accomplish this

Using str.replace()

s = "Delhi is the capital of India." 
s = s.replace('the', '123the123')
# Delhi is 123the123 capital of India.

Using .split() and enumerate()

s = "Delhi is the capital of India." 
s = s.split()
for i, v in enumerate(s):
    if v == 'the':
        s[i] = '123the123'
s = ' '.join(s)

' '.join() with a generator expression

print(' '.join("123the123" if w=="the" else w for w in s.split()))

Further reading

https://docs.python.org/3/library/stdtypes.html#string-methods https://en.m.wikipedia.org/wiki/Scunthorpe_problem

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20