简体   繁体   English

python替换字符串中的特定元素

[英]python replace specific elements in a string

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: 我有一个字符串'1472_1 2014-6-19' ,我想用“ Normal”一词替换下划线(在本例中为“ 1”)之后的任何数字,我所做的是查找我所要元素的索引要替换:

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. 但是我没有得到'1472_Normal 2014-6-19' ,而是得到了'Normal472_1 2014-6-19' 。似乎我的代码替换了下划线后的第一个,而不是第一个。

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? 我读过这篇文章: 替换字符串中的特定单词(Python),但仍然想知道是否有一种方法可以指定要替换的元素而不是使用正则表达式?

And to be clear the number after underscore could be any number from 0 to 237 要清楚的是,下划线后的数字可以是0到237之间的任何数字

You could use str.partition() : 您可以使用str.partition()

first, delimiter, second = line.partition('_')
a, s, b = second.partition(' ')
print first + delimiter + 'Normal' + s + b

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: 如果不存在正则表达式,则在基于line.find(' ')的数字之后总是有一个空格,请分割一次以分割字符串并rstrip删除任何数字:

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 您自己的代码失败的原因是因为您在字符串的开头有一个1 ,所以您将其替换为下划线之后的那个而不是

no regex 没有正则表达式

string = '1472_1 2014-6-19'
to_replace = string[string.find('_'):string.find(' ')]
string = string.replace(to_replace,'_Normal')
print string

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: 如果您不想使用RegEx,则可以使用切片来隔离要替换的字符串部分。因此,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM