close

How to replace the first character alone in a string using python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to replace the first character alone in a string using python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to replace the first character alone in a string using python?

  1. How to replace the first character alone in a string using python?

    This built in function returns 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.

  2. replace the first character alone in a string using python

    This built in function returns 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.

Method 1

In Python, strings are immutable meaning you cannot assign to indices or modify a character at a specific index. Use str.replace() instead. Here’s the function header

str.replace(old, new[, count])

This built in function returns 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.

If you don’t want to use str.replace(), you can manually do it by taking advantage of splicing

def manual_replace(s, char, index):
    return s[:index] + char + s[index +1:]

string = '11234'
print(manual_replace(string, 'I', 0))

Output

I1234

Method 2

I am not sure what you want to achive, but it seems you just want to replace a '1' for an 'I' just once, so try this:

string = "11234"
string.replace('1', 'I', 1)

str.replace takes 3 parameters oldnew, and count (which is optional). count indicates the number of times you want to replace the old substring with the new substring.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read