最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How do i replace text before a certain point in a string? - Stack Overflow

programmeradmin3浏览0评论

Below this is my code, I have a tuple of different possible extensions that the user can use to open a file. But the files that the user will open will have a name (like cat.zip or daughter.jpg). I want to remove this name (cat in the first one, daughter in the second) and replace it with "image/" followed by whatever extension they used. I would greatly appreciate it if you could help by explaining me how to figure this out.

P.S: The code may look unfinished, that's because it is. I'm trying to figure this out before continuing.

def main():
    ext = (".gif", ".jpeg", ".jpg", ".png", ".pdf", ".txt", ".zip")
    file = input("What file would you like to run? \n>> ")
    if file.endswith(ext):
        print(file.lstrip(ext))

main()

I tried using the .replace() function or .lstrip, but I couldn't figure out how to only limit the .replace function to only the text before the extension, if I use specific characters, it could mess up the extensions being printed. I am unable to use the .lstrip function with a tuple from my experience.

Below this is my code, I have a tuple of different possible extensions that the user can use to open a file. But the files that the user will open will have a name (like cat.zip or daughter.jpg). I want to remove this name (cat in the first one, daughter in the second) and replace it with "image/" followed by whatever extension they used. I would greatly appreciate it if you could help by explaining me how to figure this out.

P.S: The code may look unfinished, that's because it is. I'm trying to figure this out before continuing.

def main():
    ext = (".gif", ".jpeg", ".jpg", ".png", ".pdf", ".txt", ".zip")
    file = input("What file would you like to run? \n>> ")
    if file.endswith(ext):
        print(file.lstrip(ext))

main()

I tried using the .replace() function or .lstrip, but I couldn't figure out how to only limit the .replace function to only the text before the extension, if I use specific characters, it could mess up the extensions being printed. I am unable to use the .lstrip function with a tuple from my experience.

Share Improve this question asked Feb 17 at 4:18 CinderCinder 291 silver badge2 bronze badges New contributor Cinder is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

5 Answers 5

Reset to default 5

There are multiple ways to do this, but the simplest way is probably to use rsplit.

filename = "somefile.gif"
basename, ext = filename.rsplit(".", maxsplit=1)
replacement = "image/" + ext

you can use the split function in python for the strings to get the extension, the split function is a property of standard strings in python which takes an argument as the separator and divides the string into parts. In your case extensions are signed via a ., so you can divide the string into several parts and take the last one.

So the code should be,

def main():
    ext = ["gif", "jpeg", "jpg", "png", "pdf", "txt", "zip"]
    file = input("What file would you like to run? \n>> ")
    extension = file.split('.')[-1] # here split returns a list of divisions, the extension is the very last part of that list
    if extension in ext:
        print("images/" + extension)
    else:
        print("File extension not valid.")

main()

I am not sure what you mean by adding images/ with the extension but however you can now edit the code suitable to your program

For your specific case, you mentioned you only want to replace the start of the file. In this case, try:

def main():
    ext = (".gif", ".jpeg", ".jpg", ".png", ".pdf", ".txt", ".zip")
    file = input("What file would you like to run? \n>> ")
    for possible_end in ext:
        if file.endswith(possible_end):
            print("image" + possible_end)

main()

You need to loop through all the possible endings in the tuple, not just provide the tuple itself. This'll print 'image' + the appropriate file end. Otherwise, it won't print anything.

you could work with a sed style regular expression...

's|^.*\.([a-z]{3,4})$|image/\1|'

eg, in bash...

echo '
something.jpg
thingy.png
junk.tiff
' | sed -E 's|^.*\.([a-z]{3,4})$|image/\1|'

image/jpg
image/png
image/tiff

This captures and saves the extension with (\.[a-z]{3,4}$) (ie, whatever text is at the end of the string that has a dot followed by 3 or 4 lower case letters) then pastes the captured text (with \1) to the end of the string 'image', replacing the original basename (minus extension), which is matched by ^.*. This expression can be made case insensitive if required.

If accepted extensions need to be limited:

echo '
something.jpg
thingy.png
junk.tiff
' | sed -E 's:^.*\.(jpg|png|tiff)$:image/\1:'

image/jpg
image/png
image/tiff

This syntax (or similar) likely works in some python library like re.

[Edited to replace dot with slash...]

Using a regular expression you can both validate and isolate the components of the input string that you're interested in as follows:

import re

def main() -> str:
    ex = r"^(.+)\.(gif|jpeg|jpg|png|pdf|txt|zip)$"
    file = input("What file would you like to run? ")
    return f"image/{m.group(1)}" if (m := re.match(ex, file)) else ""

print(main())

Example:

What file would you like to run? abc.gif
image/abc
发布评论

评论列表(0)

  1. 暂无评论