'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. Sample String : 'restart' Expected Result : '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. Does this mean I can only run this code using str as a variable, or is there an alternate solution?
Solution 1:[1]
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
Solution 2:[2]
I have implemented your question in a easy way.
e="restart"
x=e[0]
e1=e.replace(x,'$')
e2=x+e1[1::]
print(e2)
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evgeny |
| Solution 2 | |
| Solution 3 | Menna |
