0

[SOLVED] String Subtraction in Python

Are there any functions to remove part of a string in Python i.e. to remove a certain phrase from the inputted string.

6th Feb 2020, 4:11 PM
Chaitanya Iyer
Chaitanya Iyer - avatar
6 Answers
+ 4
You can for example use the replace method for that. 'world'.replace('l', '') replaces l again nothing, so you get a new string 'word'. Beware - if there are more ls, all will be changed. ;) You can also use slicing to create a new string. x = 'abracadabra' print(x[:4]+x[-3:]) This leads to 'abrabra'. Slices are convenient, we have a mini tutorial about it here in the learn section.
6th Feb 2020, 4:31 PM
HonFu
HonFu - avatar
+ 5
Sami, by using replace() with strings you create a new string. You can check it with id() function: >>> txt = 'hello' >>> txt => 'hello' >>> id(txt) => 183145248 >>> txt = txt.replace('l','_') >>> txt => 'he__o' >>> id(txt) => 141764608
7th Feb 2020, 6:49 PM
Lothar
Lothar - avatar
+ 2
Hey HonFu I meant how to remove a certain phrase from an inputted string.
6th Feb 2020, 4:26 PM
Chaitanya Iyer
Chaitanya Iyer - avatar
+ 1
Can you describe more clearly what exactly you want to do? strcmp is a comparison function. In Python you can compare strings with ==. However, that's got nothing to do with subtraction, so please explain.
6th Feb 2020, 4:17 PM
HonFu
HonFu - avatar
+ 1
string.strip([chars]) is kind of similar. It removes whatever characters (or a string surrounded by ‘ ‘) you want from a string. If you don’t provide any characters, it removes any white space from either end of the original string.
6th Feb 2020, 4:19 PM
Isabel
Isabel - avatar
0
basically strings are immutable. onces you created a string you can not changed it.... but by using replace method you can change some characters of it
7th Feb 2020, 6:23 PM
Sami
Sami - avatar