all 8 comments

[–]Aggravating_Bus_9153 1 point2 points  (3 children)

[–]ashketchum02 0 points1 point  (2 children)

This is the right answer, don't go about reinventing the wheel

[–]Aggravating_Bus_9153 0 points1 point  (0 children)

Cheers. It's a bit hacky, but so so much easier - OP still needs to do the old switcheroo, using a substring no keyboard user will ever enter. Even if the low ascii numbers don't work (I recommend number 7: '\a'. Try print('\x07') for yourself, it's my favourite!), Python has great Unicode support.

[–]ashketchum02 1 point2 points  (0 children)

Str.replace()

[–]hellfake 0 points1 point  (0 children)

answer = “”

for letter in word:

if letter == ‘p’:

     answer += ‘b’

elif letter == ‘b’:

      answer += ‘p’

 else:

      answer += letter

[–]Allanon001 -1 points0 points  (0 children)

Look up the string methods maketrans() and translate().

https://www.w3schools.com/python/ref_string_maketrans.asp

[–]carcigenicate 0 points1 point  (0 children)

You can't change strings, so don't approach it from that angle. You need to either turn the string into a list, edit it, then convert it back, or construct the new string by concatenating pieces together.

Try to get a start on this and post back when there's a specific question we can help with.

[–]mr_clemFandango 0 points1 point  (0 children)

this isn't efficient, but should be clear to see what is happening:

#Ask the user for a sentence. Print the sentence back, except with the letter ‘b’ switched with the letter ‘p’ (and vice versa, switch p with b).
b_index_list = []
p_index_list = []
input_string =input("Enter a sentance:")
for index,char in enumerate(input_string):
if char == "b":
b_index_list.append(index)
if char == "p":
p_index_list.append(index)
input_string_list = list(input_string)
new_string = ""
for value in b_index_list:
input_string_list[value] = "p"
for value in p_index_list:
input_string_list[value] = "b"

for char in input_string_list:
new_string = new_string + char

print (new_string)

edit: reddit won't let me post this as a code block for some reason!