如果最后一个字符以特定字符开头和结尾,则将其大写



如果最后一个字符以"abc"开头并以"n"结尾,我需要大写。我已经编写了下面的代码,但我似乎无法让它工作,任何更正/输入都非常受欢迎

bhp['cc']=bhp['cc'].apply( lambda x:x[0:-1] + x[-1].upper() if(x.startswith('abc') & x.endswith('n')))

缺少else语句,因此apply不知道如果条件失败该怎么办。通过在if条件之后添加else x,它将起作用。

apply(lambda x:x[0:-1] + x[-1].upper() if(x.startswith('abc') & x.endswith('n')) else x)

这将最后一个字符(在n之前)大写,其余字符小写:

s = 'abcdirtybitn'
print(s[:-2].lower() + s[-2:].capitalize() if s.startswith('abc') and s.endswith('n') else s)

输出

abcdirtybiTn

如果您希望最后一个字符n大写:

print(s[:-1].lower() + s[-1:].capitalize() if s.startswith('abc') and s.endswith('n') else s)  # abcdirtybitN

编辑

如果您不想操作/小写所有其余部分:

s = 'abcDirtyBitn'
print(s[:-1] + s[-1:].capitalize() if s.startswith('abc') and s.endswith('n') else s)

输出

abcDirtyBitN

和:

s = 'abcDirtyBitn'
print(s[:-2] + s[-2:].capitalize() if s.startswith('abc') and s.endswith('n') else s)

输出

abcDirtyBiTn

我认为这可能是一个有效的解决方案:

In [47]: l
Out[47]: ['abcdfn', 'abc', 'abcn', 'Acv', 'Abc']
In [48]: df = pd.DataFrame(l)
In [49]: df
Out[49]:
0
0  abcdfn
1     abc
2    abcn
3     Acv
4     Abc
In [50]: mask = df[0].str.startswith('abc') & df[0].str.endswith('n')
In [51]: df.loc[mask, 0] = df[mask][0].apply(lambda x : x[0:-1] + x[-1].upper())
In [52]: df
Out[52]:
0
0  abcdfN
1     abc
2    abcN
3     Acv
4     Abc

最新更新