![]() |
How I could do that in the best way? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How I could do that in the best way? (/thread-38879.html) |
How I could do that in the best way? - Kalet - Dec-06-2022 Hi, I would like to know if there is a way to validate the '{}' when I receive them in a function. For example, I receive a URL and I have two parameters and I can perfectly do the .format. However, what if I have several URLs and some of them have the following model: import re def test(param): # I need here know how many {} I will receive print(param.format("google.com", "webpath")) test("http://{}/something/{}") # What's happen if I will do the next? #test("http://{}/something/{}/{}/{}/{}")It is for this reason, that maybe it could be done with re.replace, but it seems to me a rudimentary way and even so, I think it would not solve the problem: import re def test(param): print(param.format(param.replace('[host]', 'a'), param.replace('[path]',"b"))) test("http://[host]/something/[path]")Any ideas? Thank you! RE: How I could do that in the best way? - Pedroski55 - Dec-06-2022 If you get this: Quote:http://{ }/something/{ }/{ }/{ }/{ } Do you always know what goes in the { }? If not, how will you decide? RE: How I could do that in the best way? - Kalet - Dec-06-2022 (Dec-06-2022, 09:22 AM)Pedroski55 Wrote: If you get this: Yes, maximum it should be 4-5 {}, I know the values but I don't know how to validate the {} ![]() RE: How I could do that in the best way? - DeaD_EyE - Dec-06-2022 This is just checking how many parts the path has. The first part is always / .from pathlib import Path from urllib.parse import urlparse def how_many(url): return len(Path(urlparse(url).path).parts) - 1 print(how_many("http://{ }/something/{ }/{ }/{ }/{ }")) You can also do this to count the parts:len(Path("http://{ }/something/{ }/{ }/{ }/{ }".removeprefix("http://")).parts) - 1 str.removeprefix was added since Python 3.9
RE: How I could do that in the best way? - Kalet - Dec-06-2022 (Dec-06-2022, 03:35 PM)DeaD_EyE Wrote: This is just checking how many parts the path has. The first part is always Thank you, it's helpful your answer! RE: How I could do that in the best way? - Pedroski55 - Dec-07-2022 A simple way to do this, given that brackets need always be binary! mystring = "http://{ }/something/{ }/{ }/{ }/{ }" count = 0 for b in mystring: if b == '{': count +=1 print(count) |