shateep
shateep

Reputation:

finding substring

Thanks in advance. I have a string:

A = 'asdfghjklmn'

How can I get a substring having a maximum length which is a multiple of three?

Upvotes: 0

Views: 623

Answers (5)

Stephan202
Stephan202

Reputation: 61469

You can use slice notation and integer arithmetic.

>>> a = 'asdfghjklmn'
>>> a[:len(a)//3*3]
'asdfghjkl'   
>>> len(a)
11
>>> len(a[:len(a)//3*3])
9

In general, n//k*k will yield the largest multiple of k less than or equal to n.

Upvotes: 4

Mark Rushakoff
Mark Rushakoff

Reputation: 258128

With the foreword that it will never be as efficient as the ones that actually use math to find the longest multiple-of-3-substring, here's a way to do it using regular expressions:

>>> re.findall("^(?:.{3})*", "asdfghjklmn")[0]
'asdfghjkl'

Changing the 3 quantifier will allow you to get different multiples.

Upvotes: 0

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43110

Yet another example:

>>> A = '12345678'
>>> A[:len(A) - len(A)%3]
'123456'
>>> 

Upvotes: 1

SilentGhost
SilentGhost

Reputation: 319511

It seems like you're looking for something like this:

>>> A = 'asdfghjklmn'
>>> mult, _ = divmod(len(A), 3)
>>> A[:mult*3]
'asdfghjkl'

here resulting string will have length which is multiple of three and it will be the longest possible substring of A with such length.

Upvotes: 1

Lance Rushing
Lance Rushing

Reputation: 7630

Is this what you want?

A = 'asdfghjklmn'
A[0:(len(A)/3)*3]
'asdfghjkl'

Upvotes: 0

Related Questions