Python Forum
How I could do that in the best way?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How I could do that in the best way?
#1
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!
Reply
#2
If you get this:

Quote:http://{ }/something/{ }/{ }/{ }/{ }

Do you always know what goes in the { }?

If not, how will you decide?
Reply
#3
(Dec-06-2022, 09:22 AM)Pedroski55 Wrote: If you get this:

Quote:http://{ }/something/{ }/{ }/{ }/{ }

Do you always know what goes in the { }?

If not, how will you decide?


Yes, maximum it should be 4-5 {}, I know the values but I don't know how to validate the {} Undecided
Reply
#4
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/{ }/{ }/{ }/{ }"))
Output:
5
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
Kalet and carecavoador like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(Dec-06-2022, 03:35 PM)DeaD_EyE Wrote: 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/{ }/{ }/{ }/{ }"))
Output:
5
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

Thank you, it's helpful your answer!
Reply
#6
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)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020