Rahul Nair
Rahul Nair

Reputation: 23

replacing only the first occurance of a character in string

My objective is to replace the 0th string element with another string element. I tried the below code.

s='12:15:45'

s=s.replace(s[0],'9')

print(s)

While the 0th element does get replaced, the change is also reflected on the 3rd element.

output- 92:95:45

Why is this happening ?

Upvotes: 1

Views: 2529

Answers (4)

Rima
Rima

Reputation: 1455

Pass count of occurrance.

string.replace(oldvalue, newvalue, count)
  • oldvalue Required. The string to search for
  • newvalue Required. The string to replace the old value with count
  • count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

s=s.replace(s[0],'9',1)

print(s)

Upvotes: 1

Vishal Singh
Vishal Singh

Reputation: 6234

use s.replace(s[0],'9', 1) to replace only the first occurrence.


str.replace(old, new, count) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Upvotes: 1

buran
buran

Reputation: 14233

As stated in the docs:

str.replace(old, new[, count]) - Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

You don't specify count, so it replace all occurrences of s[0] - in this case '1'. In this particular case you can do

s = '12:15:45'
s = s.replace(s[0],'9',1)
print(s)

but it will not work always - e.g. if you want to replace only s[3]

Upvotes: 1

EXODIA
EXODIA

Reputation: 958

The replace function by default is replacing all the occurrences of 1 in the string. You can limit this using the correct syntax as below

Syntax

string.replace(oldvalue, newvalue, count)

If you want only the first occurrence to get replaced you should use

s=s.replace(s[0],'9',1)

Upvotes: 2

Related Questions