I want to delete the part after the last '/' of a string in this following way:
str = "live/1374385.jpg"
formated_str = "live/"
or
str = "live/examples/myfiles.png"
formated_str = "live/examples/"
I have tried this so far ( working )
import re
for i in re.findall('(.*?)/',str):
j += i
j += '/'
Output :
live/ or live/examples/
I am a beginner to python so just curious is there any other way to do that .
Use rsplit:
str = "live/1374385.jpg"
print (str.rsplit('/', 1)[0] + '/')
live/
str = "live/examples/myfiles.png"
print (str.rsplit('/', 1)[0] + '/')
live/examples/
You can also use .rindex string method:
s = 'live/examples/myfiles.png'
s[:s.rindex('/')+1]
#!/usr/bin/python
def removePart(_str1):
return "/".join(_str1.split("/")[:-1])+"/"
def main():
print removePart("live/1374385.jpg")
print removePart("live/examples/myfiles.png")
main()
Related
I have a string https://www.exampleurl.com/
How would I insert a word in the middle of a string so it could look like this: https://www.subdomain.exampleulr.com/
I know I can insert the word if I did this:
url = 'https://www.exampleurl.com/'
url[:12] + 'subdomain'
It prints me https://www.subdomain, but I can't figure out how to print the rest of the string dynamically so it would adjust to the subdomain that is being appended to the string.
My goal is for the end result to look like the following https://www.subdomain.exampleurl.com/
url = 'https://www.exampleurl.com/'
content = url.split("www.")
url = content[0] + "www." + "subdomain." + content[1]
url = 'https://www.exampleurl.com/'
text = url.split(".")
url = text[0] + '.subdomain.' + text[1] + '.' + text[2]
Final output : https://www.subdomain.exampleurl.com/
Better split on the first .:
l = url.split('.', 1)
l[0] + '.subdomain.' + l[1]
## OR if subdomain is a variable:
f'{l[0]}.{subdomain}.{l[1]}'
output: 'https://www.subdomain.exampleurl.com/'
Using replace (once)
url = 'https://www.exampleurl.com/'
url = url.replace(".", ".subdomain.", 1) # only replaces first "." to
# get desured result
I need to clean the data "{u'town': u'Bainbridge'} as only bainbridge
def clean(self,text):
if text:
return ' '.join(''.join(text).split())
ustaApproved = self.clean(raw_ustaApproved)
certifications = self.clean(raw_certifications)
Not quite clear from your post, but my guess it that {u'town': u'Bainbridge'} comes as a string. You need to parse it to a dictionary, but first, we'll turn it into JSON:
import json
def clean(text):
text = text.replace("u", "")
text = text.replace("'", '"')
return json.loads(s)
s = "{u'town': u'Bainbridge'}"
d = clean(s)
desired_value = d["town"]
# => Bainbridge
I have the below code in one of my configuration files:
appPackage_name = sqlncli
appPackage_version = 11.3.6538.0
The left side is the key and the right side is value.
Now i want to be able to replace the value part with something else given a key in Python.
import re
Filepath = r"C:\Users\bhatsubh\Desktop\Everything\Codes\Python\OO_CONF.conf"
key = "appPackage_name"
value = "Subhayan"
searchstr = re.escape(key) + " = [\da-zA-Z]+"
replacestr = re.escape(key) + " = " + re.escape(value)
filedata = ""
with open(Filepath,'r') as File:
filedata = File.read()
File.close()
print ("Before change:",filedata)
re.sub(searchstr,replacestr,filedata)
print ("After change:",filedata)
I assume there is something wrong with the regex i am using. But i am not able to figure out what . Can someone please help me ?
Use the following fix:
import re
#Filepath = r"C:\Users\bhatsubh\Desktop\Everything\Codes\Python\OO_CONF.conf"
key = "appPackage_name"
value = "Subhayan"
#searchstr = re.escape(key) + " = [\da-zA-Z]+"
#replacestr = re.escape(key) + " = " + re.escape(value)
searchstr = r"({} *= *)[\da-zA-Z.]+".format(re.escape(key))
replacestr = r"\1{}".format(value)
filedata = "appPackage_name = sqlncli"
#with open(Filepath,'r') as File:
# filedata = File.read()
#File.close()
print ("Before change:",filedata)
filedata = re.sub(searchstr,replacestr,filedata)
print ("After change:",filedata)
See the Python demo
There are several issues: you should not escape the replacement pattern, only the literal user-defined values in the regex pattern. You can use a capturing group (a pair of unescaped (...)) and a backreference (here, \1 since the group is only one in the pattern) to restore the part of the matched string you need to keep rather than build that replacement string dynamically. As the version value contains dots, you should add a . to the character class, [\da-zA-Z.]. You also need to assign new value after replacing, so as to actually modify it.
I have this Django/Python call:
Stuff = Source.object.value_list(dbtype, host)
What I want to do is create this string:
`"mssql#12.12.12.12, MySQL#23.23.23.23"`
I tried to peform a join: ",".join(Stuff.dbtype + " " + Stuff.host) and that failed miserably.
Is there a version of the join call that will do what I'm looking for without manually iterating through my object?
Thanks.
You should use values instead of values_list:
stuff = Source.objects.values('dbtype', 'host')
Then:
stuffs = [i['dbtype'] + '#' + i['host'] for i in stuff]
result = ', '.join(stuffs)
or:
def compose(stuff):
return stuff['dbtype'] + '#' + stuff['host']
temp = map(compose, stuffs)
result = reduce(lambda x, y: x + ', ' + y, temp)
Firstly, values_list return list of tuples, so you can't write Stuff.dbtype.
Secondly, str.join takes iterable object as parameter like list.
So you can rewrite your code like this:
Stuff = Source.object.values_list(dbtype, host)
result = ', '.join([dbtype + '#' + host for dbtype, host in Stuff])
I need to write into a file with Before and after search replacement patterns. I have written the below code. I have used function in writing to output file and it worked fine. But i have around 20 such replacement patterns and i feel i am not writing a good code because i need to create functions for all those replacements. Can you please let me know is there any other way in implementing this?
import re
Report_file = open("report.txt", "w")
st = '''<TimeLog>
<InTime='10Azx'>1056789</InTime>
<OutTime='14crg'>1056867</OutTime>
<PsTime='32lxn'>1056935</PsTime>
<ClrTime='09zvf'>1057689</ClrTime>
</TimeLog>'''
def tcnv(str):
Report_file.write("Previous TS: " + str + "\n\n")
v1 = re.search(r"(?i)<clrtime='(\d+\w+)'>", str)
val1 = v1.group(1)
v2 = re.search(r"(?i)(<clrtime='(\d+\w+)'>(.*?)</clrtime>)", str)
val2 = v2.group(3)
soutval = "<Clzone><clnvl='" + val1 + "'>" + val2 + "</clnvl></Clzone>"
Report_file.write("New TS: " + soutval + "\n")
return soutval
st = re.sub(r"(?i)(<clrtime='(\d+\w+)'>(.*?)</clrtime>)", lambda m: tcnv(m.group(1)), st)
st = re.sub(r"(?i)<intime='(\d+\w+)'>(.*?)</intime>", "<Izone><Invl='\\1'>\\2</Invl></Izone>", st)
st = re.sub(r"(?i)<outtime='(\d+\w+)'>(.*?)</outtime>", "<Ozone><onvl='\\1'>\\2</onnvl></Ozone>", st)
st = re.sub(r"(?i)<pstime='(\d+\w+)'>(.*?)</pstime>", "<Pszone><psnvl='\\1'>\\2</psnvl
I didn't see why you put the re.IGNORECASE flag under the form of (?i), so I don't use it the following solution, and the pattern is written with the uppercased letters where necessary according to your sample
Note that you should use the with statement to open the files, it would be far better:
with open('filename.txt','rb') as f:
ch = f.read()
The answer
import re
st = '''<InTime='10Azx'>1056789</InTime>
<OutTime='14crg'>1056867</OutTime>
<PsTime='32lxn'>1056935</PsTime>
<ClrTime='09zvf'>1057689</ClrTime>
'''
d = dict(zip(('InTime','OutTime','PsTime','ClrTime'),
(('Izone><Invl','/Invl></Izone'),
('Ozone><onvl','/onnvl></Ozone'),
('Pszone><psnvl','/psnvl></Pszone'),
('Clzone><clnvl','/clnvl></Clzone'))
)
)
def ripl(ma,d=d):
return "<{}='{}'>{}<{}>".format(d[ma.group(1)][0],
ma.group(2),
ma.group(3),
d[ma.group(1)][1])
st2 = re.sub(r"<(InTime|OutTime|PsTime|ClrTime)='(\d+\w+)'>(.*?)</\1>",
ripl, st)
print '%s\n\n%s\n' % (st,st2)