I am not sure what you want to achive, but it seems you just want to replace a '1' for an 'I' just once, so try this:
string = "11234"
string.replace('1', 'I', 1)
str.replace takes 3 parameters old, new, and count (which is optional). count indicates the number of times you want to replace the old substring with the new substring.
I am not sure what you want to achive, but it seems you just want to replace a '1' for an 'I' just once, so try this:
string = "11234"
string.replace('1', 'I', 1)
str.replace takes 3 parameters old, new, and count (which is optional). count indicates the number of times you want to replace the old substring with the new substring.
In Python, strings are immutable meaning you cannot assign to indices or modify a character at a specific index. Use str.replace() instead. Here's the function header
str.replace(old, new[, count])
This built in function returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
If you don't want to use str.replace(), you can manually do it by taking advantage of splicing
def manual_replace(s, char, index):
return s[:index] + char + s[index +1:]
string = '11234'
print(manual_replace(string, 'I', 0))
Output
I1234
python - How to replace the first two characters of a string, with the first two characters of another string? - Stack Overflow
How to find the first character of a string and replace all findings of it in the same string in Python? - Stack Overflow
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
Pattern to match first occurrence in line?
you are not using method calls properly. ie, you are defining stringMix as a function, but using variables that are out of the scope of the function. I think what you are trying to do is:
def stringMix(a,b):
print (a.replace([0:2]b[0:2]))
print (b.replace([0:2],a[0:2]))
userStringA = input("Please enter a string consisting of over two characters ")
userStringB = input("Please enter a second string consisting of over two characters ")
print (userStringA)
print (userStringB)
stringMix(userStringA,userStringB)
However, as previous answers and comments suggest, str.replace is not really the way to do this. you should instead do:
def stringMix(a,b):
print (a[0:2]+b[2:])
print (b[0:2]+a[2:])
to take advantage of string slicing and concatenating
Simply do:
print userStringB[:2] + userStringA[2:]
and
print userStringA[:2] + userStringB[2:]