John Doe Smith
John Doe Smith

Reputation: 345

Removing strings from other strings

How do I remove a part of a string like

Blue = 'Blue '
Yellow = 'Yellow'
Words = Blue + Yellow
if Blue in Words:
    Words = Words - Yellow

That is what I thought it would look like?

EDIT: I know thatit won't work I want to know what would work. Since you cant use '-' in a str()

Upvotes: 0

Views: 85

Answers (3)

voithos
voithos

Reputation: 70602

From a different perspective, you actually can't remove part of a string because strings (in Python) are immutable - they cannot be modified (for good reason). This means no assignments (mystring[0] = 'f').

What you can do is build a completely new string with the specific part it of removed. This accomplishes the same goal.

This is actually pretty important, because it implies that

mystring.replace('m', 'f')

by itself, does nothing (note that there is no assignment - this just builds a new string, and then throws it away). Learning this concept of immutability (and mutability) is essential to learn - it will help you avoid many mistakes.

Upvotes: 3

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

Use replace function:

if Blue in Words:
    Words = Words.replace(Yellow, '')

If Words is a list than you can do the following:

if Blue in Words:
   Words = [word for word in Words if word != Yellow]

Or the same but using remove:

if Blue in Words:
   Words.remove(Yellow)

Upvotes: 1

mgilson
mgilson

Reputation: 310049

You can use str.replace to exchange the text with an empty string:

Words = Words.replace(Yellow,'')

Note that this will transform:

"The Yellow Herring"

into simply:

"The Herring"

(the replacement will happen anywhere in the string). If you only want to remove 'Yellow' from the end of a string, you could use .endswith and a slice:

if Blue in Words and Words.endswith(Yellow):
    Words = Words[:-len(Yellow)]

Upvotes: 6

Related Questions