简体   繁体   中英

Python remove gibberish and everything after from a string

Just wondering if there is a way to cut all the gibberish from a string. (for example, if the string was: stackoverflowfoajfasjsdksakklsslQuestion ) How would I remove the gibberish and anything after?

The reason I am asking for this is that I have a camera that only saves things as: "Image01jsjajdiahdkasdiajdksjCameraImage" (stuff like that) and I want to remove all the stuff after the image number. It would be good if this worked with any file name, too.

If the string you want is fixed length, you can get the first characters as a new string.

#This is the full string with gibberish
fullString = 'StackOverflow1235125'

#We'd like to get StackOverflow
getString = 'StackOverflow'

#We need the length
getStringLength = getString.__len__() #This returns 13 because StackOverflow is 13 chars.

returnString = fullString[:getStringLength] #This trims the fullString, only leaving the first 13 characters.
print(returnString)

The output is

StackOverflow

I want to remove all the stuff after the image number

import re

text = "Image01jsjajdiahdkasdiajdksjCameraImage"

result = re.match(r"(.*\d+)", text)

print(result.group())

Output:

Image01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM