Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using replace() function to replace multiple texts(strings) at once in Python

Tags:

python

replace

Here's my code:

start_j = raw_input('Enter a name: ')
start_j = start.replace("A", "J")
start_j = start.replace("B", "J")
start_j = start.replace("C", "J")
print "Your name is " + start_j

Is there anyway to put all the alphabets in one list so that I wouldn't have to repeat the same process again and again until I reach letter "Z" I tried using loops, but I still can't seem to get the right way to do it.

Here's a scenario: The user will be prompted to input a name. If the name contains a letter other than "J", it will be automatically replaced using the replace() function. Hence it will print out the input starting with J

Here's an example:

site = raw_input('Enter your website: ')
site = site.replace("http://", "")
site = site.replace("https://", "")
site = site.replace("ftp://", "")
print "Your website is: " + site

An expected input would be http://www.google.com So the expected out would become:

Enter your website: http://www.google.com
Your website is: www.google.com

I'm looking for a way to put "http://", "https://", "ftp://" all in one list so I wouldn't have to enter

site = site.replace("something", "something)

many times

like image 710
Max Wayne Avatar asked Feb 18 '23 02:02

Max Wayne


2 Answers

You could use a regex to replace all of the letters at once:

>>> import re
>>> re.sub(r'[A-Z]', 'J', 'This Is A Test Name')
'Jhis Js J Jest Jame'

(After edit): You can use .startswith() and string slicing:

>>> name = 'A Name'
>>> 
>>> if not name.startswith('J'):
...     name = 'J' + name[1:]
... 
>>> name
'J Name'

Although I'm not sure why you'd even need to check with .startswith(). Either way, the result will be the same.

like image 172
Blender Avatar answered Feb 20 '23 15:02

Blender


You can use this:

remove_from_start = ["http://", "https://", "ftp://"]
for s in remove_from_start:
    if site.startswith(s):
        site = site[len(s):]
        break

Or a regular expression based solution:

import re
regex = '^(https?|ftp)://'
site = re.sub(regex, '', site)
like image 28
Mark Byers Avatar answered Feb 20 '23 14:02

Mark Byers