Suggestions to split a string into substring [duplicate] - python

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 8 years ago.
I want to split "ranganath" into something like
"ra"
"ng"
"an"
"at"
"h"
using Python. Any help would be highly appreciated.

Try with:
x = 'ranganath'
[ x[i:i+2] for i in xrange(0,len(x),2) ]

Related

How to split a string without a delimiter [duplicate]

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:]]

Split the string into words [duplicate]

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.

Split string into groups of 3 characters [duplicate]

This question already has answers here:
Split string every nth character?
(19 answers)
Closed 5 years ago.
I have a string
ddffjh3gs
I want to convert it into a list
["ddf", "fjh", "3gs"]
In groups of 3 characters as seen above.
What is the best way to do this in python 2.7?
Using list comprehension with string slice:
>>> s = 'ddffjh3gs'
>>> [s[i:i+3] for i in range(0, len(s), 3)]
['ddf', 'fjh', '3gs']

Eliminate numbers in string in Python [duplicate]

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'

Find last occurrence of character in string Python [duplicate]

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

Categories

Resources