Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdigit():
numbers. append(int(word))
elif word.isalpha():
letters.append(word)
s = f"{numbers} {letters}"
return s
Can someone help me explain my error and give me a "pro" programmers solution and "noob" (myself) solution?
This is what i should print:
a = 'New_York 10001'
s = standardize_address(a)
print(s)
and the output should be:
10001 New York
Right now my output is:
[10001] ['New', 'York']
CodePudding user response:
Issues
strings are immutable so you need to keep the replace result, so do
a = a.replace('_', ' ')
or chain it before the split callYou need to concatenate the lists into one
numbers letters
then join the elements with" ".join()
don't convert the numeric to
int
, that's useless and would force you to convert them back to str in the" ".join
def standardize_address(a):
numbers = []
letters = []
for word in a.replace('_', ' ').split():
if word.isdigit():
numbers.append(word)
elif word.isalpha():
letters.append(word)
return ' '.join(numbers letters)
Improve
In fact you want to sort the words regarding the isdigit
condition, so you can express that with a sort and the appropriate sorted
def standardize_address(value):
return ' '.join(sorted(value.replace('_', ' ').split(),
key=str.isdigit, reverse=True))
CodePudding user response:
numbers
and letters
are both lists of strings, and if you format them they'll be rendered with []
s and ''
s appropriately. What you want to do is to replace this:
s = f"{numbers} {letters}"
return s
with this:
return ' '.join(numbers letters)
numbers letters
is the combined list of number-strings and letter-strings, and ' '.join()
takes that list and turns it into a string by putting ' '
between each item.