Replace all instances of a character or word with another; Python Programming

replace

 

In the first instance we are going to replace all instances of a British Pound sign in a given sentence with that of a dollar sign. Thankfully Python has this covered, making it simple little program.

First we create our variable Sentence and assign it with input from our user.

 

Sentence = input(“Please enter a sentence:”)

 

Then we use the .replace() method to do the work for us.

We give it two arguments; the symbol we want to replace followed by what we want it replaced with. In this case its replace all instances of £ with $

We assign the results to a new variable with the very same name; Sentence

 

Sentence = Sentence.replace(‘£’,’$’)   #don’t forget the comma

 

Now all that is left is to print the variable Sentence to the screen

print(Sentence)

 

The full program:

Sentence = input(“Please enter a sentence:”)

Sentence = Sentence.replace(‘£’,’$’)

print(Sentence)

 

We could of course use this little program to replace a full word; like replace apple with orange

Our first line will remain the same.

Sentence = input(“Please enter a sentence:”)

 

Our second line of course will be changed to meet the new criteria

Sentence = Sentence.replace(‘apple’, ‘orange’)

 

We need to take account that someone may capitalize Apple and Orange, so we add a line to our code to capture this.

Sentence = Sentence.replace(‘Apple’, ‘Orange’)

 

And of course we print just like the last program

print(Sentence)

 

Full Program:

Sentence = input(“Please enter a sentence:”)

Sentence = Sentence.replace(‘apple’, ‘orange’)

Sentence = Sentence.replace(‘Apple’, ‘Orange’)

print(Sentence)

 

Lets input a sentence like, I do love an apple in the morning. You should eat an Apple every day…

Simple!

http://www.unleashthepython.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s