2

I'm trying to isolate a substring of each string element of an array such that it is the string until the last period. For example I would want to have:

input = 'A.01.0'
output = 'A.01'

or

input = 'A.0'
output = 'A'

And I want to do this for all elements of an array.

1
  • 3
    This sounds like homework. How about posting what you've got so far and what specifically you're stuck on. Strings have two functions 'split' and 'join' which you'll find useful. Commented Aug 30, 2011 at 22:47

3 Answers 3

3

Use some rsplit magic:

x=["123","456.678","abc.def.ghi"]
[y.rsplit(".",1)[0] for y in x]
Sign up to request clarification or add additional context in comments.

Comments

0

This is one way to produce the wanted output format. You need to alter this to suit your needs.

output = input[:input.rindex('.')]

For the entire array:

arr = ['A.01.0', 'A.0']
arr = [x[:x.rindex('.')] for x in arr]

Hope that helps :-)

Comments

-1

Something like this?

>>> i = ['A.01.0', 'A.0']
>>> [x[:x.rfind('.')] for x in i]
['A.01', 'A']

1 Comment

rfind returns -1 if the character is not found, so "abc"[:"abc".rfind('.')] will become "ab" and not "abc". That's why rsplit is more appropriate here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.