Home > Software engineering >  In python, how to append a string without quotation marks next to a string with the single quotation
In python, how to append a string without quotation marks next to a string with the single quotation

Time:03-02

url = https://www.amazon.com//Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}

def getData(url):
    new_link = 'f'  str(url)


###rest of the code

The coding above gives the following output:

'fhttps://www.amazon.com//Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'

However, the letter f should be outside of the quotation marks surrounding the url. That is, I am seeking the following:

f'https://www.amazon.com/Best-Sellers-Electronics/zgbs/electronics/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'

CodePudding user response:

What C. Pappy said, but in addition, take a look at the format method.

CodePudding user response:

Formatted string literals in Python are strings that are prefixed by f or F and whose contents have a special semantics. The f is not a character that is part of the string; you can think of it as a modifier for the string that follows. You cannot construct such a literal by simply concatenating the f character with some string.

There are several ways to achieve your goal. The first (as other answers suggest) uses the simpler approach. If however you insist on separating the URL and dynamically generating and using the formatted string literal, see the second. The third uses a format string (identical to the url in the second).

  1. Use the formatted string literal directly:

    def getData(pageNo):
      new_link = f'https://www.amazon.com/Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'
      # rest of the code
    
  2. Use eval:

    url = 'https://www.amazon.com/Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'
    
    def getData(url, pageNo):
       new_link = eval("f'"  url   "'"))
       # rest of the code
    
  3. Use .format:

    url = 'https://www.amazon.com/Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'
    
    def getData(url, pageNo):
       new_link = url.format(pageNo=pageNo)
       # rest of the code
    

CodePudding user response:

I think you want ro do something like this:

pageNo = 123
url = f'https://www.amazon.com//Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_{pageNo}?_encoding=UTF8&pg={pageNo}'
print(url)

which prints:

https://www.amazon.com//Best-Sellers-Amazon-Launchpad/zgbs/boost/ref=zg_bs_pg_123?_encoding=UTF8&pg=123

For more information on Python's format strings see https://realpython.com/python-f-strings/

  • Related