user3685742
user3685742

Reputation: 275

Replacing end numbers in a string python

Basically, I have scraped some tennis scores from a website and dumped them into a dictionary. However, the scores of tiebreak sets are returned like "63" and "77". I want to be able to add a starting parenthesis after the 6 or 7 and close the parentheses at the end of the entire number. So a pseudo code example would be:

>>>s = '613'
>>>s_new = addParentheses(s)
>>>s_new
6(13)

The number after the 6 or 7 can be a one or two digit number from 0 onwards (extremely unlikely that it will be a 3 digit number, so I am leaving that possibility out). I tried reading through some of the regex documentation on the Python website but am having trouble incorporating it in this problem. Thanks.

Upvotes: 2

Views: 95

Answers (3)

CT Zhu
CT Zhu

Reputation: 54330

Just add two parentheses at the 2nd and last position? Seems too easy:

In [42]:

s = '613'
def f(s):
    L=list(s)
    L.insert(1,'(')
    return "".join(L)+')'
f(s)
Out[42]:
'6(13)'

Or just ''.join([s[0],'(',s[1:],')'])

If you situation is simple, go for a simple solution, which will be faster. The more general a solution is, the slower it is likely to be:

In [56]:

%timeit ''.join([s[0],'(',s[1:],')'])
100000 loops, best of 3: 1.88 µs per loop
In [57]:

%timeit f(s)
100000 loops, best of 3: 4.97 µs per loop
In [58]:

%timeit addParentheses(s)
100000 loops, best of 3: 5.82 µs per loop
In [59]:

%timeit re.sub(r"^([67])(\d{1,2})$", r"\1(\2)", s)
10000 loops, best of 3: 22 µs per loop

Upvotes: 1

Akavall
Akavall

Reputation: 86168

What about something like this:

def addParentheses(s):
    if not s[0] in ('6','7'):
        return s
    else:
        temp = [s[0], '(']
        for ele in s[1:]:
            temp.append(ele)
        else:
            temp.append(')')
    return ''.join(temp)

Demo:

>>> addParentheses('613')
'6(13)'
>>> addParentheses('6163')
'6(163)'
>>> addParentheses('68')
'6(8)'
>>> addParentheses('77')
'7(7)'
>>> addParentheses('123')
'123'

Upvotes: 1

zx81
zx81

Reputation: 41838

If the strings always start with 6 or 7, you're looking for something like:

result = re.sub(r"^([67])(\d{1,2})$", r"\1(\2)", subject)

Explain Regex

^                        # the beginning of the string
(                        # group and capture to \1:
  [67]                   #   any character of: '6', '7'
)                        # end of \1
(                        # group and capture to \2:
  \d{1,2}                #   digits (0-9) (between 1 and 2 times
                         #   (matching the most amount possible))
)                        # end of \2
$                        # before an optional \n, and the end of the
                         # string

The replacement string "\1(\2) concatenates capture Group 1 and capture Group 2 between parentheses.

Upvotes: 4

Related Questions