How to replace the first character alone in a string using python?
string = "11234"
translation_table = str.maketrans({'1': 'I'})
output= (string.translate(translation_table))
print(output)
Expected Output:
I1234
Actual Ouptut:
11234
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
You can use re (regex), and use the sub function there, first parameter is the thing you want to replace, and second is the thing that you want to replace with, third is the string, fourth is the count, so i say 1 because you only want the first one:
>>> import re
>>> string = "11234"
>>> re.sub('1', 'I', string, 1)
'I1234'
>>>
It's virtually just:
re.sub('1', 'I', string, 1)
Related
After initializing a variable x with the content shown in below, I applied strip with a parameter. The result of strip is unexpected. As I'm trying to strip "ios_static_analyzer/", "rity/ios_static_analyzer/" is getting striped.
Kindly help me know why is it so.
>>> print x
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/
>>> print x.strip()
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/
>>> print x.strip('/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer
>>> print x.strip('ios_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu
>>> print x.strip('analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_
>>> print x.strip('_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static
>>> print x.strip('static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('s_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io
>>> print x.strip('os_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu
Quoting from str.strip docs
Return a copy of the string with the leading and trailing characters
removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None, the chars argument
defaults to removing whitespace. The chars argument is not a prefix or
suffix; rather, all combinations of its values are stripped:
So, it removes all the characters in the parameter, from both the sides of the string.
For example,
my_str = "abcd"
print my_str.strip("da") # bc
Note: You can think of it like this, it stops removing the characters from the string when it finds a character which is not found in the input parameter string.
To actually, remove the particular string, you should use str.replace
x = "/Users/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/"
print x.replace('analyzer/', '')
# /Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_
But replace will remove the matches everywhere,
x = "abcd1abcd2abcd"
print x.replace('abcd', '') # 12
But if you want to remove words only at the beginning and ending of the string, you can use RegEx, like this
import re
pattern = re.compile("^{0}|{0}$".format("abcd"))
x = "abcd1abcd2abcd"
print pattern.sub("", x) # 1abcd2
What you need, I think, is replace:
>>> x.replace('ios_static_analyzer/','')
'/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/'
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new.
So you can replace your string with nothing and get the desired output.
Python x.strip(s) remove from the begginning or the end of the string x any character appearing in s ! So s is just a set of characters, not a string being matched for substring.
string.strip removes a set of characters given as an argument. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
strip does not remove the string given as argument from the object; it removes the characters in the argument.
In this case, strip sees the string s_static_analyzer/ as an iterable of characters that needs to be stripped.
I have a list which is of the following format:
[ '2013,june,25,11,img1.ams.expertcity.com,/builds/g2m/1172/G2M_Mac_x86,84.83.189.112,3', '2013,june,25,11,img1.ams.expertcity.com,/builds/g2m/1172/G2MInstallerExtractor.exe,85.164.14.248,6', '2013,june,25,11,img1.syd.expertcity.com,/builds/g2m/1172/G2MCoreInstExtractor.exe,99.245.80.126,19']
I need to replace only the first three commas with '-' for each element of the list i.e the list should look like this:
[ '2013-june-25-11,img1.ams.expertcity.com,/builds/g2m/1172/G2M_Mac_x86,84.83.189.112,3', '2013-june-25-11,img1.ams.expertcity.com,/builds/g2m/1172/G2MInstallerExtractor.exe,85.164.14.248,6', '2013-june-25-11,img1.syd.expertcity.com,/builds/g2m/1172/G2MCoreInstExtractor.exe,99.245.80.126,19']
I tried to use replace but it ends up replacing all ',' with '-'
mylist = [x.replace(",","-") for x in mylist]
I do not want to use regex because the order in the list might change over time.
Please suggest a better way to do this?
Use this : x.replace(",","-",3)
str.replace has a third optional argument count.
help on str.replace:
S.replace(old, new[, count]) -> string
Return a copy of string S with all occurrences of substring old
replaced by new. If the optional argument count is given, only the
first count occurrences are replaced.
basically I want to change the first "." to "_"
Name.1001.ext to Name_1001.ext:
I have something like this but it is returning the original name:
print re.sub(r'\D+.\d+\.$',r'\D+_\d+\.$',fileName)
Regex seems like an overkill for this example, you should probably go for str.replace() here:
In [16]: strs="Name.1001.ext"
In [17]: strs.replace(".","_",1) # now only 1 occurrence of the
# substring is going to be replaced
Out[17]: 'Name_1001.ext'
S.replace(old, new[, count]) -> string
Return a copy of string S with all occurrences of substring old
replaced by new. If the optional argument count is given, only the
first count occurrences are replaced.
Is it possible to replace a single character inside a string that occurs many times?
Input:
Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input
^
Sentence=("This is an Example. This code is not what I'm having problems with.") #Desired output
Replace the 'x' in "Thxs" with an i, without replacing the x in "Example".
You can do it by including some context:
s = s.replace("Thxs", "This")
Alternatively you can keep a list of words that you don't wish to replace:
whitelist = ['example', 'explanation']
def replace_except_whitelist(m):
s = m.group()
if s in whitelist: return s
else: return s.replace('x', 'i')
s = 'Thxs example'
result = re.sub("\w+", replace_except_whitelist, s)
print(result)
Output:
This example
Sure, but you essentially have to build up a new string out of the parts you want:
>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> s[22]
'x'
>>> s[:22] + "i" + s[23:]
"This is an Example. This code is not what I'm having problems with."
For information about the notation used here, see good primer for python slice notation.
If you know whether you want to replace the first occurrence of x, or the second, or the third, or the last, you can combine str.find (or str.rfind if you wish to start from the end of the string) with slicing and str.replace, feeding the character you wish to replace to the first method, as many times as it is needed to get a position just before the character you want to replace (for the specific sentence you suggest, just one), then slice the string in two and replace only one occurrence in the second slice.
An example is worth a thousands words, or so they say. In the following, I assume you want to substitute the (n+1)th occurrence of the character.
>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> n = 1
>>> pos = 0
>>> for i in range(n):
>>> pos = s.find('x', pos) + 1
...
>>> s[:pos] + s[pos:].replace('x', 'i', 1)
"This is an Example. This code is not what I'm having problems with."
Note that you need to add an offset to pos, otherwise you will replace the occurrence of x you have just found.
I would like to remove the first character of a string.
For example, my string starts with a : and I want to remove that only. There are several occurrences of : in the string that shouldn't be removed.
I am writing my code in Python.
python 2.x
s = ":dfa:sif:e"
print s[1:]
python 3.x
s = ":dfa:sif:e"
print(s[1:])
both prints
dfa:sif:e
Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.
If you only need to remove the first character you would do:
s = ":dfa:sif:e"
fixed = s[1:]
If you want to remove a character at a particular position, you would do:
s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]
If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:
s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))
Depending on the structure of the string, you can use lstrip:
str = str.lstrip(':')
But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.
Just do this:
r = "hello"
r = r[1:]
print(r) # ello
deleting a char:
def del_char(string, indexes):
'deletes all the indexes from the string and returns the new one'
return ''.join((char for idx, char in enumerate(string) if idx not in indexes))
it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])