How to remove the first occurrence of a character from a string in Python

2 Answers

0 votes
string = "c c++ python java python php"

char = 'p'

length = len(string)

for i in range(length):
    if (string[i] == char):
        string = string[0:i] + string[i + 1:length]
        break
  
print(string)




'''
run:

c c++ ython java python php

'''

 



answered Apr 16, 2022 by avibootz
0 votes
string = "c c++ python java python php"

char = 'p'

string = string.replace(char, "", 1)

print(string)




'''
run:

c c++ ython java python php

'''

 



answered Apr 16, 2022 by avibootz
...