1

I have a string '1472_1 2014-6-19' and I want to replace whatever number is after the underscore(in this case number one) with the word 'Normal', what I did was to find the index of the element that I want replaced:

print line.replace(line[line.find('_') + 1:line.find(' ')],'Normal', 1)

But instead of getting '1472_Normal 2014-6-19', I got 'Normal472_1 2014-6-19' It seems like my code replace the first 1 instead of the one after the underscore.

I have read this post: Replacing specific words in a string (Python) but still wondering is there a way to specify which element to be replaced instead of using regex?

And to be clear the number after underscore could be any number from 0 to 237

Community
  • 1
  • 1
Enkri_
  • 161
  • 2
  • 12

4 Answers4

3

You could use str.partition():

first, delimiter, second = line.partition('_')
a, s, b = second.partition(' ')
print first + delimiter + 'Normal' + s + b
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2

without regex if there is always a space after the digit which based on line.find(' ') there is, split once to divide the string and rstrip any digits:

s = '1472_1 2014-6-19'

a,b = s.split(None,1)

print("{}Normal {}".format(a.rstrip("0123456789"),b))) 
1472_Normal 2014-6-19  

stripping will work for any amount of digits after the underscore.

With regex:

 import  re

s = '1472_1 2014-6-19'

print(re.sub("(?<=_)\d+","Normal",s))
1472_Normal 2014-6-19

Why your own code fails is because you have a 1 at the start of your string so you replace that not the one after the underscore

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

no regex

string = '1472_1 2014-6-19'
to_replace = string[string.find('_'):string.find(' ')]
string = string.replace(to_replace,'_Normal')
print string
Community
  • 1
  • 1
taesu
  • 4,482
  • 4
  • 23
  • 41
1

If you don't want to use RegEx, you could use slicing to isolate the section of the string to replace in. So for instance:

def replace_normal(s)
    ui = s.index('_')  # index of first underscore
    si = s.index(' ')  # index of first space
    return s[:ui+1] + 'Normal' + s[si:]

s1 = '1472_1 2014-6-19'
s2 = '1571_44 2014-7-24'

print replace_normal(s1)  # 1472_Normal 2014-6-19
print replace_normal(s2)  # 1571_Normal 2014-7-24
Bob Dylan
  • 1,773
  • 2
  • 16
  • 27