Consider I have a string in the format
sampleapp-ABCD-1234-us-eg-123456789. I need to extract the text ABCD-1234. Its more like I need ABCD and then the numbers before the -
Please let me know how can i do that
-
Can you please help @ManojKumarwanderors– wanderors2022年03月18日 11:39:07 +00:00Commented Mar 18, 2022 at 11:39
-
If the number characters is fixed, then you can use string slicing.Manoj Kumar– Manoj Kumar2022年03月18日 11:40:25 +00:00Commented Mar 18, 2022 at 11:40
-
No...it can vary @ManojKumarwanderors– wanderors2022年03月18日 11:41:11 +00:00Commented Mar 18, 2022 at 11:41
4 Answers 4
You could use string.split(), so it would be:
string = 'sampleapp-ABCD-1234-us-eg-123456789'
example = string.split('-')
Then you can access 'abcd' and '1234' as example[1] and example[2] respectively. You can also join them back together into one string if needs be with string.join().
string = 'sampleapp-ABCD-1234-us-eg-123456789'
example = string.split('-')
newstring = ' '.join(example[1:3])
print (newstring)
You can also change the seperator, '-'.join would make it so the output is 'ABCD-1234' rather than 'ABCD 1234'.
6 Comments
You can use Regex (Regular expression) Here's the Python script you can use:
import re
txt = "sampleapp-ABCD-1234-us-eg-123456789"
x = re.findall("([ABCD]+[-][0-9]+)", txt)
print(x)
More varied version:
x = re.findall("([A-Z]{4}[-][0-9]+)", txt)
For more info about Regex you can learn it here: regexr.com
Hope this helps. Cheer!
8 Comments
You can do that :
txt = "sampleapp-ABCD-1234-us-eg-123456789"
abcd = txt[10:14]
digits = txt[15:19]
print(abcd)
print(digits)
You can also use split the text using txt.split("-") and then you can extract what you want :
abcd = txt.split("-")[1]
digits = txt.split("-")[2]
Comments
Please keep this post as an enquiry if it doesn't answer your question.
If what your are saying is that the string is of the form a-B-X0-c-d-X1 and that you want to extract B-X0 from the string then you can do the following:
text = 'a-B-X0-c-d-X1'
extracted_val = '-'.join(text.split('-')[1:3])