0

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

3
  • Can you please help @ManojKumar Commented Mar 18, 2022 at 11:39
  • If the number characters is fixed, then you can use string slicing. Commented Mar 18, 2022 at 11:40
  • No...it can vary @ManojKumar Commented Mar 18, 2022 at 11:41

4 Answers 4

2

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'.

Sign up to request clarification or add additional context in comments.

6 Comments

I think should solve your problem.
can we get using regex ?
You could, but if the text you need is always going to be in the same position there's honestly no point.
can we make like the text ABCD and the the number before the next -, like that format ?
Do you mean so it's one string? Like 'ABCD-1234'? I'll add it to the answer above.
|
2

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

It didnt work..
Can you show me the output? I want to know why it didn't work.
It printed as []
Can I see the code?
x = re.findall("([GEST]+[-][0-9]+)", STRING) print("XXXXXXX") print(x) String provided was JustTrial-GEST-1234-ty-eg-123456789
|
0

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

0

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])

1 Comment

if you were asking something else ,let me know

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.