+ 1

Removing specified character from string in Python

I'm trying to solve task for finding first word in a given text. But I need to remove "," from end of a word if there is one. How can I do that ?

11th Mar 2018, 11:05 AM
Mher Khachatryan
Mher Khachatryan - avatar
6 Réponses
+ 2
Strings are immutable, that means you can't modify it (to be exact, you can't perform remove, add, change operation on it). So, all you can do is first change to mutable type (i.e list) and remove specific character. And reconstruct string by joining them. Here's how you do it: https://code.sololearn.com/ct3KLHrnoXp6/?ref=app PS. If your aim is just to search first word of string and no comma in it, then you should try regular expression (in python, there's "re" module). It gives you more power in searching string.
11th Mar 2018, 11:53 AM
Sylar
+ 1
Ahh, i forgot that method. Thanks Obbu :) btw don't you think replace method do same mechanism as i mention? I think because string cannot modify directly?
11th Mar 2018, 12:35 PM
Sylar
0
it is true that strings are immutable but you can use the replace() function to replace characters in a string with something else eg. i = 'h,e,l,l,o,' if ',' in i: i = i.replace(',' , '' ) print (i)
11th Mar 2018, 12:18 PM
Obbu
Obbu - avatar
0
it will do that or iterate through the whole string and change each one independently
11th Mar 2018, 9:45 PM
Obbu
Obbu - avatar
0
I have tried replace method , but for given task, I can't do anything with it.
12th Mar 2018, 8:49 AM
Mher Khachatryan
Mher Khachatryan - avatar
0
Sylar, thank you. You guessed what I'm trying to do. I appreciate your support. Thank you guys.
12th Mar 2018, 8:50 AM
Mher Khachatryan
Mher Khachatryan - avatar