![](/img/trans.png)
[英]How can I replace the last character of a string for the first letter of the alphabet?
[英]How do I replace all instances of the first letter in a string, but not the first letter itself
到目前为止,我的代码是:
def ChangeString():
print (userString.replace(
userString =str(input("Please enter a string "))
ChangeString()
在字符串中,我需要用*替换第一个字符的所有实例,而不必实际替换第一个字符本身。 例如,假设我有“泡泡”; 该函数将返回类似“ Bo ** le”的信息。
>>> test = 'Bobble'
>>> test = test[0] +''.join(l if l.lower() != test[0].lower() else '*' for l in test[1:])
>>> print test
Bo**le
userString[0] + userString[1:].replace(userString[0], "*")
您还可以使用正则表达式:
import re
def ign_first(s, repl):
return re.sub(r"(?<!^){}".format(s[0]), repl, s, flags=re.I)
演示:
In [5]: s = "Bobble"
In [6]: ign_first(s, "*")
Out[6]: 'Bo**le'
或将str.join
与集合一起使用:
def ign_first(s, repl):
first_ch = s[0]
st = {first_ch, first_ch.lower()}
return first_ch + "".join([repl if ch in st else ch for ch in s[1:]])
演示:
In [10]: ign_first(s, "*")
Out[10]: 'Bo**le'
我将使用slices和lower()
。
>>> test = 'Bobble'
>>> test[0] + test[1:].lower().replace(test[0].lower(), '*')
'Bo**le'
无需使用其他变量
>>> st='Bobble'
>>> st=st[0]+st[1:].lower().replace(st[0].lower(),'*')
>>> st
'Bo**le'
具有正则表达式的不区分大小写的解决方案:
import re
string = "Bobble"
outcome = string[0]+re.sub(string[0].lower() + '|' + string[0].upper(),
"*", string[1:].lower())
>>>
Bo**le
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.