patternpythonMinor
Can this list comprehension be made more pythonic?
Viewed 0 times
thiscomprehensioncanpythonicmademorelist
Problem
Quite a specific question can the below code be made more clearer / pythonic in any way.
Essentially based on the condition of the string
Essentially based on the condition of the string
x((len(x) / 3) - 1), I use this to extract out parts of the string.def split_string(x):
splitted_string = [x[counter*3:(counter*3)+3] for counter in range ((len(x) /3) - 1)]
return splitted_string
>>> split_string('ABCDEFGHI')
['ABC', 'DEF']Solution
For integer division, use the
The task could be more succinctly accomplished using
Also, the goal of the function is not obvious. Pythonic code would include a docstring explaining its purpose.
// operator. In Python 3, / will do floating-point division.The task could be more succinctly accomplished using
re.findall().Also, the goal of the function is not obvious. Pythonic code would include a docstring explaining its purpose.
import re
def split_string(s):
"""
Splits a string into a list, with each element consisting of
three characters. Any incomplete group at the end is discarded,
and then the last complete group is also discarded.
"""
return re.findall(r'.{3}', s)[:-1]Code Snippets
import re
def split_string(s):
"""
Splits a string into a list, with each element consisting of
three characters. Any incomplete group at the end is discarded,
and then the last complete group is also discarded.
"""
return re.findall(r'.{3}', s)[:-1]Context
StackExchange Code Review Q#46849, answer score: 6
Revisions (0)
No revisions yet.