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']
Issues
strings are immutable so you need to keep the replace result, so do a = a.replace('_', ' ') or chain it before the split call
You 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))
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.
Related
I am very new to programming, so sorry for a basic question. I am trying to write a function that will take a string in which words are divided by ',' and return a list of these words (the Split method). My code is:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list + ['']
return my_shop_list
print(str_to_list("Milk,Cottage,Tomatoes")) should look like [Milk, Cottage, Tomatoes]
but I am keep getting IndexError: list index out of range.
I read some answers here and couldn't find something to work.
Can anyone explain what is wrong.
list has the method append so a solution will be something like this:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list.append('')
return my_shop_list
PS: Do not forgot about empty spaces between words in string like "aaa, bbb, ccc" will be ['aaa', ' bbb', ' ccc'] with spaces.
def sp(s):
l =[]
while True:
comma = s.find(',')
if comma == -1:
l.append(s)
break
l.append(s[:comma])
s = s[comma+1:]
print(l)
this is a simplified version hope it helps.
Simplest Way:
We can use an inbuilt split function.
def Convert(string):
# split the string whenever "," occurs
# store the splitted parts in a list
li = list(string.split(","))
return li
# Driver code
str1 = "Hello,World"
print(Convert(str1))
Output:
["Hello", "World"]
What is the most efficient way to remove spaces from a text, and then after the neccessary function has been performed, re-insert the previously removed spacing?
Take this example below, here is a program for encoding a simple railfence cipher:
from string import ascii_lowercase
string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
This outputs the following:
hlooltdyelwrdoa
This is because it must remove the spacing prior to encoding the text. However, if I now want to re-insert the spacing to make it:
hlool tdyel wrdoa
What is the most efficient way of doing this?
As mentioned by one of the other commenters, you need to record where the spaces came from then add them back in
from string import ascii_lowercase
string = "Hello World Today"
# Get list of spaces
spaces = [i for i,x in enumerate(string) if x == ' ']
string = string.replace(" ", "").lower()
# Set string with ciphered text
ciphered = (string[::2] + string[1::2])
# Reinsert spaces
for space in spaces:
ciphered = ciphered[:space] + ' ' + ciphered[space:]
print(ciphered)
You could use str.split to help you out. When you split on spaces, the lengths of the remaining segments will tell you where to split the processed string:
broken = string.split(' ')
sizes = list(map(len, broken))
You'll need the cumulative sum of the sizes:
from itertools import accumulate, chain
cs = accumulate(sizes)
Now you can reinstate the spaces:
processed = ''.join(broken).lower()
processed = processed[::2] + processed[1::2]
chunks = [processed[index:size] for index, size in zip(chain([0], cs), sizes)]
result = ' '.join(chunks)
This solution is not especially straightforward or efficient, but it does avoid explicit loops.
Using list and join operation,
random_string = "Hello World Today"
space_position = [pos for pos, char in enumerate(random_string) if char == ' ']
random_string = random_string.replace(" ", "").lower()
random_string = list(random_string[::2] + random_string[1::2])
for index in space_position:
random_string.insert(index, ' ')
random_string = ''.join(random_string)
print(random_string)
I think this might Help
string = "Hello World Today"
nonSpaceyString = string.replace(" ", "").lower()
randomString = nonSpaceyString[::2] + nonSpaceyString[1::2]
spaceSet = [i for i, x in enumerate(string) if x == " "]
for index in spaceSet:
randomString = randomString[:index] + " " + randomString[index:]
print(randomString)
string = "Hello World Today"
# getting index of ' '
index = [i for i in range(len(string)) if string[i]==' ']
# storing the non ' ' characters
data = [i for i in string.lower() if i!=' ']
# applying cipher code as mention in OP STATEMENT
result = data[::2]+data[1::2]
# inserting back the spaces in there position as they had in original string
for i in index:
result.insert(i, ' ')
# creating a string solution
solution = ''.join(result)
print(solution)
# output hlool tdyel wrdoa
You can make a new string with this small yet simple (kind of) code:
Note this doesn't use any libraries, which might make this slower, but less confusing.
def weird_string(string): # get input value
spaceless = ''.join([c for c in string if c != ' ']) # get spaceless version
skipped = spaceless[::2] + spaceless[1::2] # get new unique 'code'
result = list(skipped) # get list of one letter strings
for i in range(len(string)): # loop over strings
if string[i] == ' ': # if a space 'was' here
result.insert(i, ' ') # add the space back
# end for
s = ''.join(result) # join the results back
return s # return the result
Let´s say I have a one-word string ("Hello") and I wanted to swap the first and last letter so I´d do this:
s="Hello"
l=list(s)
l[0],l[len(l)-1]=l[len(l)-1],l[0]
print("".join(l))
But, what if I had to swap the first and last letter in every word of the string:"Hello World" , so that I would get "oellH dorlW".
I was thinking using nested lists but it seems overcomplicated.
Strings are immutable, so you can create a new one by slicing:
s = "Hello"
>>> s[-1] + s[1:-1] + s[0]
"oellH"
To do multiple words, split and rejoin as follows:
s= "Hello World"
>>> ' '.join(word[-1] + word[1:-1] + word[0] for word in s.split())
'oellH dorlW'
You can split your string, swap letters for each word and .join() it back together:
# example is wrong, does not swap, only puts first in the back. see below for fix
text = ' '.join( t[1:]+t[0] for t in "Hello World".split() )
print (text)
Output:
elloH orldW
This uses list comprehensionst to extract each splitted word (t) - list slicing to move the front letter to its back (t[1:]+t[0]) and ' '.join() to make the list of strings back to a string.
Links:
What exactly does the .join() method do? and str.join()
Understanding Python's slice notation (for lists, strings are similar)
str.split()
It also works for longer strings:
elloH orldW si a eallyr verusedo trings ermt - orF ureS !
As pointed out by #Accumulation I misread the question - my example simply puts the first letter to the end of the string thats only halve the work done for swapping first and last letter:
# t[-1] is the last character put to the front,
# followed by t[1:-1] 1st to (but not including) the last character
# followed by t[0] the first character
text = ' '.join( t[-1]+t[1:-1]+t[0] for t in "Hello World".split() )
print (text)
Output:
oellH dorlW
string = "Hello Planet Earth"
Make a list of words by splitting on space char
words = string.split(" ")
Then iterate on that list with your script
for word in words:
l = list(word)
l[0], l[len(l) - 1] = l[len(l) - 1], l[0]
print("".join(l))
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 6 years ago.
I was trying to write something to capitalize each word in a sentence. And it works fine, as follows:
print " ".join((word.capitalize() for word in raw_input().strip().split(" ")))
If the input is 'hello world', the output would be :
Hello World
But I tried writing it differently as follows :
s = raw_input().strip().split(' ')
for word in s:
word.capitalize()
print ' '.join(s)
And its output would be wrong :
hello world
So what's wrong with that, why the result isn't the same ?! Thank you.
The problem in your code is that strings are immutable and you are trying to mutate it. So if you wont to work with loop you have to create new variable.
s = raw_input().strip().split(' ')
new_s = ''
for word in s:
new_s += s.capitalize()
print new_s
Or, It would work if you use enumerate to iterate over list and update s:
s = raw_input().strip().split(' ')
for index, word in enumerate(s):
s[index] = .capitalize()
print ' '.join(s)
But the best way to capitalize words in string is to use str.title() - method for capitalization of words in string:
s = 'hello word'
print(s.title())
print ' '.join([i.capitalize() for i in raw_input('Enter text here:').split(' ')])
This will solve you problem.
Strings are immutable and you are trying to update the same value which is not poassible.
Create a new string and update in that way.
s = raw_input().strip().split(' ')
st = ''
for word in s:
st+= word.replace(word,word.capitalize())
print ''.join(st)
Or
print " ".join([i.capitalize() for i in raw_input().strip().split(" ")])