views:

744

answers:

11

I would like my code to look beautiful
Thanks in advance..

A: 
s = 'a.pdf'
print s.replace('pdf', 'jpg')

That what you're looking for?

Daniel May
It's a simple solution, but will fail if you have a file called "CopyOfMyPdf.jpg". maybe s.replace('.pdf','.jpg') would be better, but still not perfect
ZombieSheep
yup..this looks like the most beautiful :)
Rohit
This is a very assumptive solution.
Ben James
very bad solution
SilentGhost
Actually, maybe the . needs escaping because its a special character... Should the regex be "\.[pP][dD][fF]$" so import re a top of file then re.sub('\.[pP][dD][fF]$','.jpg',s) in function?
martinr
ROFL - this is the answer the question deserves.
Pascal
I'm not going to vote either up or down because I agree with both SilentGhost and SanHolo so I would have no idea which way to go...
Greg Beech
This wasn't meant to be precisely what you were looking for ;) - I giggled when it was accepted.
Daniel May
Quick, someone upvote this 11 times so I have a shot at the populist badge :P
Daniel Bruce
Totally up for that. :P
Daniel May
@Daniel Bruce: I'd rather downvote the question, so you could get Reversal badge.
SilentGhost
Beauty first;) Then clarity: donedVersion = re.compile( '\.pdf$', re.I).sub( input, '.jpg')
martinr
I'msure don't have to tell you gentlemen (and ladies) that os.path.splitext might or might not not be appropriate for the platform the string is being processed on in these examples, as opposed to the platform it will be used to actually open a file on, as it might not be for the filesystem of the current host.
martinr
+6  A: 

i don't know if it's elegant:

  • string.replace:

    >>> s = "a.pdf"
    >>> s.replace(".pdf", ".jpg")
    

    'a.jpg'

  • regular expression:

    >>> import re
    >>> re.sub("\.pdf$", ".jpg", "a.pdf")
    'a.jpg'
    
  • os.path

    >>> import os.path
    >>> name, ext = os.path.splitext("a.pdf")
    >>> "%s.jpg" % (name)
    'a.jpg'
    
  • string index:

    >>> s = "a.pdf"
    >>> s[-3:] == "pdf" and s[:-3] + "jpg"
    'a.jpg'
    
The MYYN
some of your solutions are imperfect. ".pdf$", for instance, matches "xpdf" as well as ".pdf". And of course, the string replace will do wrong things with all sorts of input.
Bryan Oakley
"\.pdf$" doesn't match "xpdf" because the regular expression is explicitly looking for a dot before the extension.
kiamlaluno
@kiamlaluno, the original was broken. You're looking at an edited version, so the comments are "stale".
Peter Hansen
@kiamlaluno: when I made my comment there was no backslash before the dot in the regex.
Bryan Oakley
+38  A: 

The most "correct" way of doing this would be something like the following. This would handle it no matter what the extension is, regardless of platform, and generally without reinventing the wheel.

import os.path
root, ext = os.path.splitext('a.pdf')

# Optional error checking, if necessary:
if ext.lower() != '.pdf':
    raise ValueError('File lacks proper extension')

filename = "%s.jpg" % (root,)
Daniel Bruce
Congratulations on your Reversal badge, I had the final downvote ;)
Daniel May
Welcome to the Reversal club. Come out back and we'll teach you the secret handshake. (It's not really that secret; you just have to turn around and use your left hand behind your back.)
Michael Myers
nicely done! and with a reversal to boot
curtisk
Thank-you all. :)
Daniel Bruce
+2  A: 

Not the most elegant perhaps, but safer:

root, ext = os.path.splitext(s)
if ext != '.pdf':
    # Error handling
else:
    s = root + '.jpg'
Mark Byers
+1  A: 
>>> s = 'a.pdf'
>>> s[-3:]=="pdf" and s[:-3]+"jpg"
'a.jpg'
+3  A: 

Use the $ from regex to make sure you replace the file extension.

>>> import re
>>> s = 'my_pdf_file.pdf'
>>> re.sub('\.pdf$', '.jpg', s)
'my_pdf_file.jpg'
jellybean
".pdf$" matches "xpdf" as well as ".pdf" and thus will do far more than merely replace the literal string .pdf with something else.
Bryan Oakley
You've got a \. there
jellybean
I see what you did there.
Paul McGuire
@jellybean: There wasn't a \ before the "." when I made my comment.
Bryan Oakley
+1  A: 

I's suggest 1ch1g0's solution, but instead of s[-3:]=='pdf': s.endswith('.pdf') and no '+' for strings which is slow:

>>> s = 'a.pdf'
>>> s.endswith('.pdf') and ''.join([s[:-3], 'jpg'])
'a.jpg'
Karol
`+` is slow compared to `join` when concatenating many strings, for just a few `+` is much faster: 47ns vs 237ns in my machine, measured with `timeit`.
fortran
A: 

Easy:

string s="a.pdf";
s="a.jpg";

I am afraid your question leaves much to be desired...

Thomas X.
This is not Python code
codeape
It is not orange juice either...
Thomas X.
+1  A: 

Strings are immutable in Python, so basically you cannot alter it.

If you want a new string, there are plenty of options, depending on what you exactly want.

def silly_thing(s):
    return s[:-4]+".jpg" if s[-4:] == ".pdf" else s
fortran
+1 Beat me to it by 10 months! Also, as long as we're being overly *literal* (wait for it...), one should just say __return "a.jpg";__ (...see? a pun!).
+1  A: 

This one requires NumPy, but of course that means it will run much faster than the alternatives:

>>> s = 'a.pdf'
>>> from numpy import array
>>> ''.join([chr(c) for c in (array([ord(c) for c in s]) + [0, 0, -6, 12, 1])])
'a.jpg'

Of course, whether you consider this "elegant" or not depends on your definition of "elegant" but, as with all other useful information, the question didn't include that...

Edit: yes, this is a joke, but trying to make a point...

Peter Hansen
you're joking, right?
SilentGhost
Definitely... I figured it would be obvious. Too subtle?
Peter Hansen
Besides, how else am I going to get the Peer Pressure badge? Someone else, vote me down! :)
Peter Hansen
jokes are usually posted as community wiki
SilentGhost
Thanks, SilentGhost... didn't know that. I would assume that tends to give the joke away though. Made CW.
Peter Hansen
+1. I for one think this is a nice solution.
codeape
Community wiki requirement or not, this joke is hilarious.
Jarret Hardie
A: 

With some inspiration from @Peter Hansen's answer I managed to create a function that accomplishes pretty much what you need. While his approach is nice, it is a bit lacking in that it can only convert file names that are exactly 5 characters long.

My solution fixes that:

from numpy import array

def convert_pdf_filename_to_jpg_filename_in_a_really_really_elegant_way(s):
    """
    Examples:
    >>> convert_pdf_filename_to_jpg_filename_in_a_really_really_elegant_way("a.pdf")
    'a.jpg'
    >>> convert_pdf_filename_to_jpg_filename_in_a_really_really_elegant_way("myfile.pdf")
    'myfile.jpg'
    """
    return ''.join([chr(c) for c in (array([ord(c) for c in s]) + list([0] * (len(s) - 3) + [-6, 12, 1]))])

I am quite satisfied with this code. I would not mind if it was added to the Python standard library (perhaps in a really_really_elegant_code module?). But than that would require that numpy was added to the standard library as well. Does anyone have an idea if that is likely to happen?

codeape