Created
August 19, 2016 16:39
-
-
Save derekmhewitt/47b5dff3bc5debc1566cc607f0adb4c2 to your computer and use it in GitHub Desktop.
Python 401 Weekly Challenge #2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sample_string = "I am a very long string with some extra words that are silly." | |
def smart_substr(string, terminate="..."): | |
if len(string) < 30: | |
return string | |
else: | |
list_of_words = sample_string.split() | |
output = "" | |
while len(output) < 30: | |
if (len(list_of_words[0]) + len(output)) < 30: | |
output.join(list_of_words[:1]) # this is not working | |
list_of_words.pop(0) | |
print(len(output)) | |
print("joined word") | |
else: | |
output.join(terminate) | |
print("I'm in a loop") | |
break | |
return output | |
# got help from: | |
# http://stackoverflow.com/questions/6905636/python-conditional-list-joins | |
# https://docs.python.org/2/library/string.html#string.join | |
# http://stackoverflow.com/questions/4426663/how-do-i-remove-the-first-item-from-a-python-list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a few things that could be improved here. First, remember that join is called on the string you want to use to join the list of strings you pass as the argument. So
" ".join([[output] + list_of_words[0])
would work where your line 12 does not. Second, remember that you can iterate directly through a list of words, so rather than having to use thelist.pop(0)
method to shorten the list, you can just grab your words one at a time and use them directly. Your approach here is sound, but your execution is problematic. It's mostly due to familiarity with your tools. This will improve (and it has improved already).