This question already has answers here:
Understanding slicing
(38 answers)
Changing one character in a string
(15 answers)
Closed 1 year ago.
I know how to replace characters, but I would like to have the instance done once. My code replace's all the characters before.
string = "Forever9999"
string = string[:-4] + string[-4:].replace("9", "1")
Which in the end would be Forever1999, but I get Forever1111
Any help appreciated.
You can pass another paramter to str.replace(old, new[, count]), which is the max count of occurrences you want to replace:
string.replace("9", "1", 1)
# 'Forever1999'
Related
This question already has answers here:
Given a string how can I remove all the duplicated consecutive letters?
(5 answers)
Closed 1 year ago.
How can i make a basic function with def in python that removes duplicate letters from a string?
Example: input: "abbcdddea"; output: "abcdea"
This code removes duplicates but conserves the order:
string = "abb"
string_without_duplicates = "".join(dict.fromkeys(string))
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
Remove final character from string
(5 answers)
Closed 1 year ago.
How can I get the last character of this string?
seed_name = "Cocoa"
As shown in the official Python tutorial,
>>> word = 'Python'
[...]
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character
'n'
This question already has answers here:
Count the number of occurrences of a character in a string
(26 answers)
Closed 3 years ago.
how do you check if a string has more than one specific character in python. Example The string, 'mood' would clearly have two 'o' characters
You can use the str.count method:
>>> 'mood'.count('o') > 1
True
>>>
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
How to move the first letter of a word to the end
(3 answers)
Closed 4 years ago.
Let's say I have an input:
SA3213023215
I want to move the SA to the very end of the input.
How can I do this?
Assuming that SA3213023215 is a string (which input is by default), you could use string slicing:
s = "SA3213023215"
s2 = s[2:] + s[:2]
# yields 3213023215SA
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
Closed 7 years ago.
I have the following string: "aaaabbbb"
How can I get the last four characters and store them in a string using Python?
Like this:
>>> mystr = "abcdefghijkl"
>>> mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:
>>> mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
str = "aaaaabbbb"
newstr = str[-4:]
See : http://codepad.org/S3zjnKoD