[英]Problem in python program where we get a string from a given one and replace all occurrences of its first character with '$' sign
This is the full question: Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.这是完整的问题:编写一个 Python 程序从给定字符串中获取一个字符串,其中第一个字符的所有出现都已更改为“$”,第一个字符本身除外。 Sample String: 'restart' Expected Result: 'resta$t'示例字符串:'restart' 预期结果:'resta$t'
The code I gave was as follows:我给出的代码如下:
e="Test string"
f=""
for k in range(0,len(e)):
if(str[k]==e[0]):
f+="$"
else:
f+=e[k]
print("New string: ",f)
The error I got back was in this line: if(str[k]==e[0]): The error shown was TypeError: 'type' object is not subscriptable I made an observation that if I replaced the variable e with str, I get the result without issues.我得到的错误是在这一行: if(str[k]==e[0]): The error shown was TypeError: 'type' object is not subscriptable我观察到如果我用 str 替换变量 e ,我得到的结果没有问题。 Does this mean I can only run this code using str as a variable, or is there an alternate solution?这是否意味着我只能使用 str 作为变量运行此代码,还是有替代解决方案?
This works like you want, I think:这就像你想要的那样工作,我认为:
e = "test String"
f = e[0]
for char in e[1:]:
if char == e[0]:
f+="$"
else:
f+=char
print(f)
# tes$ S$ring
Though I have a suspicion there must be some more pythonic way虽然我怀疑肯定有一些更蟒蛇的方式
I have implemented your question in a easy way.我以一种简单的方式实现了您的问题。
e="restart"
x=e[0]
e1=e.replace(x,'$')
e2=x+e1[1::]
print(e2)
quote="If you cannot make it good, at least make it look good."
quoteList = list(quote)
for i in range(len(quoteList)):
quoteList[0] = "$"
if quoteList[i] == " ":
quoteList[i+1] = "$"
"".join(quoteList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.