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.
Related
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 :)
print('345nov'.rstrip('nov'))
the code above prints what you would expect: 345
So why does print('345v'.rstrip('nov')) print the same thing. The string doesn't end with "nov". It only ends with "v". But rstrip() strips it all the same. Either way, how can I make it ignore this behavior and not strip anything unless the ending string matches it exactly.
You get this behavior because rstrip() actually takes an iterable for its parameter. That means the string you place in ("nov") is interpreted as ['n', 'o', 'v']. This can be proved further by changing the order of the characters:
>>>"345nov".rstrip("nvo")
345
You can use endswith and index the string:
string = '345v'
suffix = 'nov'
if string.endswith(suffix):
string = string[:-len(suffix)]
I ended up doing something similar to #a_guest.
def rstrip(a, b):
if a.endswith(b):
return a[:-len(b)]
return a
I am currently writing a JES program that returns True or False dependent on whether a string containing a palindrome is passed to it. Although the program works, it fails when a capital letter or punctuation symbol is present. How could I get it to work?
print(ThisPalindrome("racecar"))
>> True
print(ThisPalindrome("Racecar"))
>> False
To solve the issue with capitalization, you could try using the str.lower() method in your checks.
def ThisPalindrome(word):
lowercase = word.lower()
reversedOrder = reversed(lowercase)
if lowercase == ''.join(reversedOrder):
return True
else:
return False
In theory, this function should work with basic punctuation too, as long as it doesn't break the function. Input such as ' could cause it to break.
The toLowerCase() method to return the calling string value converted to lowercase.
The replace() method to return a new string with some or all matches of a pattern replaced by a replacement. We will use one of the RegExp we just created earlier.
The split() method splits a String object into an array of strings by separating the string into sub strings.
The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
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
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.