以下是我的数据:
Data Here 94/452O
Data more 94/4522i
Data bla 94/111
Data bla 94/459es
Data bla 94/444
items
由以前的代码自动生成,但可能会出现如下:
items = ["Data Here 94/452O", "Data more 94/4522i", "Data bla 94/111", "Data bla 94/459es", "Data bla 94/444"]
现在我正在追加以下内容:
"\n".join(items).replace("4ke", "9")
和其他几个.replaces但是我希望它用大写字母替换/更改数字末尾的字符而不是小写...
输出:
Data Here 94/452O
Data more 94/4522I
Data bla 94/111
Data bla 94/459ES
Data bla 94/444
答案 0 :(得分:4)
items = ["Data Here 94/452O", "Data more 94/4522i", "Data bla 94/111", "Data bla 94/459es", "Data bla 94/444"]
items = [item[:-2] + item[-2:].upper() for item in items]
print items
<强>输出强>
['Data Here 94/452O', 'Data more 94/4522I', 'Data bla 94/111', 'Data bla 94/459ES', 'Data bla 94/444']
答案 1 :(得分:4)
使用regex
:
>>> import re
>>> items = ["Data Here 94/452O", "Data more 94/4522i", "Data bla 94/111", "Data bla 94/459es", "Data bla 94/444"]
>>> for item in items:
... print re.sub(r'([a-z]+)$', lambda m:m.group(1).upper(), item)
...
Data Here 94/452O
Data more 94/4522I
Data bla 94/111
Data bla 94/459ES
Data bla 94/444
答案 2 :(得分:2)
将切片表示法与str.upper
:
>>> item = "Data bla 94/459es"
>>> item[:-2]
'Data bla 94/459'
>>> item[-2:]
'es'
>>> item[-2:].upper()
'ES'
>>> item[:-2] + item[-2:].upper()
'Data bla 94/459ES'
>>> items = ["Data Here 94/452O", "Data more 94/4522i", "Data bla 94/111", "Data bla 94/459es", "Data bla 94/444"]
>>> [item[:-2] + item[-2:].upper() for item in items]
['Data Here 94/452O', 'Data more 94/4522I', 'Data bla 94/111', 'Data bla 94/459ES', 'Data bla 94/444']
答案 3 :(得分:2)
在每一行上试试这个。这是最简单的答案,使用切片:
line = line[:-2] + line[-2:].upper()
以上假设最后出现两个字母;注意upper()
对数字没有任何影响,因此使用它是完全安全的。例如:
line = 'Data bla 94/111'
line[:-2] + line[-2:].upper()
=> 'Data bla 94/111'
line = 'Data bla 94/459es'
line[:-2] + line[-2:].upper()
=> 'Data bla 94/459ES'
答案 4 :(得分:2)
没有正则表达式的解决方案:
print "\n".join(["%s %s" % (" ".join(x.split()[0:-1]), x.split()[-1].upper()) for x in items])
输出:
Data Here 94/452O
Data more 94/4522I
Data bla 94/111
Data bla 94/459ES
Data bla 94/444