a = "kava"
a = a.replace(a[3:], "-" * (len(a) - 3))
print(a)
In words without multiple characters is it OK. For example "kavo". But in "aaaa" replace all characters. I expected kav- but get k-v-
Dont know why, can you help me? Thank you
The issue arises because Python's replace
method replaces all occurrences of a specific character in a string. For instance, when attempting to replace the last character "a" in "kava" with a dash ("-"), all instances of "a" in the string get replaced, resulting in "k-v-". In the case of "aaaa", since all characters are the same, you end up with just "-".
If your goal is to replace only the last N characters of a string with dashes, you should use string slicing and concatenation instead of the replace
method. For example:
a = "kava"
# Replace the last N characters with dashes
N = 1
a = a[:-N] + "-" * N
print(a) # Output: kav-
If the intention is to replace the last occurrence of a letter in the string you can use the .rindex()
method to find its index. Strings are immutable in Python so it needs to be converted to a list and the replacement value assigned to the element at the determined index. A new string is then created from the updated list.
a = "kava"
# Get the index of the last occurrence of 'a'
last_index = a.rindex("a")
# Create a list from the string
a_list = [_ for _ in a]
# Replace the letter at 'last_index' position
a_list[last_index] = "-"
# Create a new string
a = "".join(a_list)
print(a) # Output: 'kav-'
Let's go through your code and see what you do there:
a = "kava"
a = a.replace(a[3:], "-" * (len(a) - 3))
print(a)
You assign a string a
with the value "kava". Then you take anything from the character at index 3 (counting starts from 0), which is just the last "a" and use it as the string to replace in str.replace()
.
The replacement string is a string of hyphens repeated... one time. This is just a single '-'.
A shorter way to write the line would be
a.replace('a', '-')
Looking at the documentation of str.replace(old, new[, count])
:
Return a copy of the string with all occurrences of substring old replaced by new.
And that's what happens: all 'a's are replaced with a hyphen. The result is "k-v-".
If you cant to replace only the last letter, you could just slice the string to get anything but the last letter and append a hyphen:
a = "kava"
a[:-1] + "-"
print(a)
# kav-
a.replace()
? You could use a temporary variable to find out, too. I believe that code there only serves to confuse you.