Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Trying to concatenate a simple string into a URL

Tags:

python

I've a variable "title" that I've scraped from a website page that I want to use as the file name. I've tried many combinations to no avail. What is wrong with my code?

f1 = open(r'E:\Dp\Python\Yt\' + str(title) + '.txt', 'w')

Thank you,

like image 844
Creek Barbara Avatar asked Mar 28 '26 06:03

Creek Barbara


1 Answers

The syntax highlighting in the question should help you out. A \' does not terminate the string -- it is an escaped single tick '.

As this old answer shows, it is actually impossible to end a raw string with a backslash. Your best option is to use string formatting

# old-style string interpolation
open((r'E:\Dp\Python\Yt\%s.txt' % title), 'w')
# or str.format, which is VASTLY preferred in any modern Python
open(r'E:\Dp\Python\Yt\{}.txt'.format(title), 'w')
# or, in Python 3.6+, the new-hotness of f-strings
open(rf'E:\Dp\Python\Yt\{title}.txt', 'w')

Or else add even more string concatenation, which seems measurably worse.

open(r'E:\Dp\Python\Yt' + "\\" + str(title) + '.txt', 'w')
like image 138
Adam Smith Avatar answered Mar 29 '26 18:03

Adam Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!