Please explain what is going on with this:
'aaaaaaaaaaa'.replace('aaa','')
Output!:
'aa'
I expected only 3 'aaa' to be replaced in the original string. Please suggest an explanation or better approach.
'aaaaaaaaaaa'.replace('aaa','',1)
Apparently the function accepts the number of replacements as a third argument!
the official documentation of the "replace" method states
Return 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 want to replace only the first occurrence of "aaa" write.
'aaaaaaaaaaa'.replace('aaa', '', 1)
The .replace() function will replace every instance of your first parameter with your second parameter. Since your original String contained 11 characters, 3 sets of "aaa" were replaced by 3 sets of "", leaving only "aa" behind.
If you only want to replace one set of "aa" we can use a different approach using indexing and substrings:
Using the .index() function we can find the first instance of "aaa". Now, we can simply remove this section from our String:
index = x.index('aa')
x = x[0: index] + x[index + 2:]
print(x)
I hope this helped! Please let me know if you need any further details or clarification :)
Related
I am trying to change the first letter of the string so that it is upper case. I know it is posible to use capitalize() or title() but I am just testing things out and wanted to know how I could do the same thing with upper(). The code I've tried comes up with error message: 'TypeError: newS must be a string on line 10'. Any suggestions would be very much appreciated!
def uppercase(string):
string = string.replace(string[0],string[0].upper)
return string
print uppercase("hello")
You missed () while calling upper which is a method:
def uppercase(string):
string = string.replace(string[0],string[0].upper(), 1)
return string
print(uppercase("hello"))
Also, as deceze pointed the replace() based approach will fail as is and you can use the optional maxreplace parameter to 1 to only replace the first occurrence.
You might do
def uppercase(string):
string = string.replace(string[0],string[0].upper(),1)
return string
print uppercase("hello")
Note that there is .upper() i.e. method is called and 1 limit number of replacements, so aaa would became Aaa rather than AAA. This solution assumes string will never be empty str.
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.
s = 'myName.Country.myHeight'
required = s.split('.')[0]+'.'+s.split('.')[1]
print required
myName.Country
How can I get the same 'required' string with better and shorter way?
Use str.rpartition like this
s = 'myName.Country.myHeight'
print s.rpartition(".")[0]
# myName.Country
rpartition returns a three element tuple,
1st element being the string before the separator
then the separator itself
and the the string after the separator
So, in our case,
s = 'myName.Country.myHeight'
print s.rpartition(".")
# ('myName.Country', '.', 'myHeight')
And we have picked only the first element.
Note: If you want to do it from the left, instead of doing it from the right, we have a sister function called str.partition.
You have a few options.
1
print s.rsplit('.',1)[0]
2
print s[:s.rfind('.')]
3
print s.rpartition('.')[0]
Well, that seems just fine to me... But here are a few other ways I can think of :
required = ".".join(s.split(".")[0:2]) // only one split
// using regular expressions
import re
required = re.sub(r"\.[^\.]$", "", s)
The regex only works if there are no dots in the last part you want to split off.
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.
I need to get the value after the last colon in this example 1234567
client:user:username:type:1234567
I don't need anything else from the string just the last id value.
To split on the first occurrence instead, see Splitting on first occurrence.
result = mystring.rpartition(':')[2]
If you string does not have any :, the result will contain the original string.
An alternative that is supposed to be a little bit slower is:
result = mystring.split(':')[-1]
foo = "client:user:username:type:1234567"
last = foo.split(':')[-1]
Use this:
"client:user:username:type:1234567".split(":")[-1]
You could also use pygrok.
from pygrok import Grok
text = "client:user:username:type:1234567"
pattern = """%{BASE10NUM:type}"""
grok = Grok(pattern)
print(grok.match(text))
returns
{'type': '1234567'}