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.
Related
In Python, how do you get the last and second last element in string ?
string "client_user_username_type_1234567"
expected output : "type_1234567"
Try this :
>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'
You can also use re.findall:
import re
s = "client_user_username_type_1234567"
result = re.findall('[a-zA-Z]+_\d+$', s)[0]
Output:
'type_1234567'
There's no set function that will do this for you, you have to use what Python gives you and for that I present:
split slice and join
"_".join("one_two_three".split("_")[-2:])
In steps:
Split the string by the common separator, "_"
s.split("_")
Slice the list so that you get the last two elements by using a negative index
s.split("_")[-2:]
Now you have a list composed of the last two elements, now you have to merge that list again so it's like the original string, with separator "_".
"_".join("one_two_three".split("_")[-2:])
That's pretty much it. Another way to investigate is through regex.
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)
I have a str in python like below. I want extract a substring from it.
table='abc_test_01'
number=table.split("_")[1]
I am getting test as a result.
What I want is everything after the first _.
The result I want is test_01 how can I achieve that.
Here is the code as already given by many of them
table='abc_test_01'
number=table.split("_",1)[1]
But the above one may fail in situations when the occurrence is not in the string, then you'll get IndexError: list index out of range
For eg.
table='abctest01'
number=table.split("_",1)[1]
The above one will raise IndexError, as the occurrence is not in the string
So the more accurate code for handling this is
table.split("_",1)[-1]
Therefore -1 will not get any harm because the number of occurrences is already set to one.
Hope it helps :)
To get the substring (all characters after the first occurrence of underscore):
number = table[table.index('_')+1:]
# Output: test_01
You could do it like:
import re
string = "abc_test_01"
rx = re.compile(r'[^_]*_(.+)')
match = rx.match(string).group(1)
print(match)
Or with normal string functions:
string = "abc_test_01"
match = '_'.join(string.split('_')[1:])
print(match)
Nobody mentions that the split() function can have an maxsplit argument:
str.split(sep=None, maxsplit=-1)
return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).
So the solution is only:
table.split('_', 1)[1]
You can try this:
Edit: Thanks to #valtah's comment:
table = 'abc_test_01'
#final = "_".join(table.split("_")[1:])
final = table.split("_", 1)[1]
print final
Output:
'test_01'
Also the answer of #valtah in the comment is correct:
final = table.partition("_")[2]
print final
Will output the same result
I have some strings I created with elements coming from many sources, number of elements will vary each time the program is run; I created a sample string that my program creates now.
I want to count in [:-3] for the following string and delete the last comma:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
So my string looks like:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
I just cant quite get there, help appreciated.
To remove the third last character from the string you can use:
string[:-3] + string[-2:]
>>> string = "hellothere"
>>> string[:-3] + string[-2:]
'hellothre'
I would use rsplit to split on the right most occurrence of a substring (limiting to two results) and then join them with an empty string
''.join(s.rsplit(',', 2))
a = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
a[:len(a) - 2] + a[len(a) - 1:]
You could obviously use different expressions in the brackets, I just wanted to show that you could use any expressions you wanted.
you can try with rfind to find the last comma
s = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
idx = s.rfind(",")
s[:idx]+s[idx+1:]
you get,
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
Using regex:
>>> print re.sub(r ",(?=[^.]*$)", r '', s)
{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}
This will match a ',' all before a any potential NOT ','. It matches the last ',' right before the end of a string.
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.