patternpythonMinor
Join strings with different delimiters and some possibly empty strings
Viewed 0 times
withpossiblyemptyjoindifferentsomeandstringsdelimiters
Problem
I want to construct a string from several substrings, each one of those with a different delimiter. If the string is present, the delimiter and the string should be added, if not, none of them should be added.
This is my current code that looks a bit dirty to me:
My problem is basically an extension of join 4 strings to the one if they are not empty in python with the addition of using different delimiter strings.
This is my current code that looks a bit dirty to me:
def my_join(major, minor, patch=None, pre_release=None, build=None, revision=None):
version = '.'.join(filter(None,(major, minor, patch)))
if pre_release: version += '-%s' % pre_release
if build: version += '+b%s' % build
if revision: version += '.%s' % revision
return versionmy_join('0', '1',pre_release='alpha')
'0.1-alpha'
my_join('2','3','4', build='567', revision='aabbcc440')
'2.3.4+b567.aabbcc440'My problem is basically an extension of join 4 strings to the one if they are not empty in python with the addition of using different delimiter strings.
Solution
It doesn't look too bad to me; I'd make a few changes.
Instead of building the string piece-by-piece, this code adds the needed parts to a list which is then
def my_join(major, minor, patch=None, prerelease=None,
build=None, revision=None):
version_parts = ['.'.join((major, minor, patch or ''))]
if prerelease:
version_parts.append('-%s' % prerelease)
if build:
version_parts.append('+b%s' % build)
if revision:
version_parts.append('.%s' % revision)
version = ''.join(version_parts)
return versionInstead of building the string piece-by-piece, this code adds the needed parts to a list which is then
joined at the end. I also removed the overpowered call to filter, and instead used or to make the patch value be '' if patch is False-ish, as it would be if patch is None.Code Snippets
def my_join(major, minor, patch=None, prerelease=None,
build=None, revision=None):
version_parts = ['.'.join((major, minor, patch or ''))]
if prerelease:
version_parts.append('-%s' % prerelease)
if build:
version_parts.append('+b%s' % build)
if revision:
version_parts.append('.%s' % revision)
version = ''.join(version_parts)
return versionContext
StackExchange Code Review Q#102071, answer score: 8
Revisions (0)
No revisions yet.