I am new to strings and I have am trying to swap characters based on their indices
If either index is invalid (i.e., something besides 0, 1, 2, ... , len(x) - 1), the function should return None.
x =0
i = 0
j = 0
def swap(x, i, j):
x = (input("Enter a string: "))
i = int(input("first number swap: "))
j = int(input("Second number swapped: "))
for ch in range(i, j):
print(x[i:j])
if ch not in range(i, j):
print("None")
swap(x, i, j)
I tried using this function but I get a repeat based on input j, minus the letters excluded based on input i
#input for x = sloth
#input for i = 4
#input for j = 1
#will equal = lot x3
Instead I want the character at index 4 to be switched with character at index 1, but if it is not in the range of those characters, then the program should return 'none'
can anyone show me what I am doing wrong?
CodePudding user response:
If the function is supposed to take x
, i
, and j
as arguments, you should use those arguments, not call input()
inside the function. If you want to use input()
to get the arguments, do that before you call the function.
Since strings are immutable, you can't simply swap the characters, so I suggest building a new string via slicing:
def swap(x, i, j):
i, j = sorted((i, j))
try:
return x[:i] x[j] x[i 1:j] x[i] x[j 1:]
except IndexError:
return None
print(swap(
input("Enter a string: "),
int(input("first number swap: ")),
int(input("Second number swapped: "))
))
Enter a string: abcdefg
first number swap: 2
Second number swapped: 4
abedcfg
Another option might be to convert x
to a mutable sequence (like a list
) so you can do the swap, and then join
it back into a string to return it:
def swap(x, i, j):
y = list(x)
try:
y[i], y[j] = y[j], y[i]
return ''.join(y)
except IndexError:
return None