This question already has answers here:
Find index of last occurrence of a substring in a string
(12 answers)
Closed 8 years ago.
How would I find the last occurrence of a character in a string?
string = "abcd}def}"
string = string.find('}',last) # Want something like this
You can use rfind:
>>> "abcd}def}".rfind('}')
8
Related
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
Closed 2 years ago.
How can I split the string '07:05:45PM' into ['07:05:45', 'PM'] in Python?
Have you tried something like:
a = ‘07:05:45PM‘
b = [a[:-2], a[-2:]]
This question already has answers here:
Convert a list with strings all to lowercase or uppercase
(13 answers)
Closed 4 years ago.
I have a list that has 12 elements. I am getting an input and matching that input with the value of another variable. Now that means that case-sensitivity will be a problem. I know how to go through the list with a loop but how can I convert every character in each element to a lowercase character?
for i in sa:
# something here to convert element in sa to lowercase
A simple one liner:
lowercase_list = [ i.lower() for i in input_list ]
This question already has answers here:
Split string every nth character?
(19 answers)
Closed 4 years ago.
how to split a string into words of 2 letters. Like given string is "HelloThere" now i want to make it ["He","ll","oT","he","re"]. Please help to code that in python.
yourList = []
yourString = "HelloThere"
while yourString:
yourList.append(yourString[:2])
yourString = yourString[2:]
If you print yourList, you will get the result.
This question already has answers here:
Remove characters from beginning and end or only end of line
(5 answers)
Closed 4 years ago.
So, I have the following string "........my.python.string" and I want to remove all the "." until it gets to the first alphanumeric character, is there a way to achieve this other than converting the string to a list and work it from there?
You can use re.sub:
import re
s = "........my.python.string"
new_s = re.sub('^\.+', '', s)
print(new_s)
Output:
my.python.string
This question already has answers here:
Remove specific characters from a string in Python
(26 answers)
Removing numbers from string [closed]
(8 answers)
Closed 8 years ago.
I’d like to eliminate numbers in a string in Python.
str = "aaaa22222111111kkkkk"
I want this to be "aaaakkkkk".
I use re.sub to replace, but it doesn't work:
str = "aaaa22222111111kkkkk"
str = re.sub(r'^[0-9]+$',"",str)
Maybe, this replaces a string which only contains numbers with "".
How should I do with this?
your regex is wrong:
re.sub(r'[0-9]',"",str)
should work:
>>> str="aaaa22222111111kkkkk"
>>> re.sub(r'[0-9]',"",str)
'aaaakkkkk'