简体   繁体   中英

Python Loop replace a part of string

I am making a project using Jupyter Notebook. I am creating an oversimplified example here.

I have a url, lets say

url=www.instagram.com/alex

I need to create a database by adding url with replace function in column adjacent to names And I have a pandas data frame

Names
John
Cherry 
nancy

Results wanted using function

Names    url
John     wwww.instagram.com/john
Cherry   www.instagram.com/cherry
nancy    www.instagram.com/nancy

What I am doing is:

data["url"] = url
w = data.names.values
def replace()
   for i in w,data.iteritems:
      for j in range(len(data.url),data.iteritems:
         data["url"]=url.replace("alex",i(j))
         return data

It throws an error that I cannot use range as indices... so I tried many things to use integers, but it still doesn't give me the results until I manually put i(0) or i(1) or i(3) If I try to add another for line like

for w in range(len(data.url):

And do i(w).. Then it changes everything to the i(0) that in this example will be www.instagram.com/john

I have used oversimplified example for my problem, in my project it is very important to create function because url is too big and the names are input (user selects) so that is why i need to creaTe function

data["url"] = "www.instagram.com/" + data["Names"].str.lower()

Please check below:

df['url'] = df['Name'].apply(lambda x : url.replace('alex',x.lower()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM