Python value assignment does not print - python

I'm a student and have a question. I'm not getting the correct output in our textbook.
first = 'I'
second = 'love'
third = 'Python'
sentence = first + '' + second + '' + third + '.'
Output:
I love Python.
When I run it, nothing happens. Can someone explain why? Thanks in advance!

print sentence. Will print the outut
But from what you have this will output "IlovePython." not I love Python.
This is because ther is no space between your '' tags. To fix this convert all those '' to ' '. Save the last one, which is . as it should be.

Your sentence variable should be:
sentence = first + ' ' + second + ' ' + third + '.'
and after assigning the value to sentence you have to print it:
print (sentence)
Also you can print directly the concatenation without saving it into a variable:
print (first + ' ' + second + ' ' + third + '.')

Related

how to remove spaces in between of a string in python?

Suppose I have a string : ' Swarnendu Pal is a good boy '
Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '
Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...
s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
if i == " ":
start_space += 1
else:
break
for i in s[::-1]:
if i == " ":
end_space += 1
else:
break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)
# " SwarnenduPalisagoodboy " #### output
Hope this helps...
An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):
>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '

How to move a white space in a string?

I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.

How do you append a list in a while loop without overwriting previous results

I'm writing a script for a grocery list for my course on Python. Everything looks good, except every time I append my list with a new dictionary entry, I overwrite the old values. I found a lot of similar questions on here already, but I hate to admit that I didn't quite understand a lot of the answers yet. Hopefully I can understand it a little better if I ask the question myself and know the context. Here is my code:
grocery_item = {}
grocery_history = []
stop = 'c'
while stop == 'c':
item_name = input('Item name:\n')
quantity = input('Quantity purchased:\n')
cost = input('Price per item:\n')
grocery_item = {'name':item_name, 'number': int(quantity), 'price':
float(cost)}
grocery_history.append(grocery_item) <<< # OVERWRITES OLD VALUES.
stop = input("Would you like to enter another item?\nType 'c' for
continue
or 'q' to quit:\n")
grand_total = 0
for items in range(0,len(grocery_history)):
item_total = grocery_item['number'] * grocery_item['price']
grand_total = grand_total + item_total
print(str(grocery_item['number']) + ' ' + str(grocery_item['name']) + '
' + '#' + ' ' + '$' + str(grocery_item['price']) + ' ' + 'ea' + ' ' +
'$' +
str(item_total))
item_total == 0
print('Grand total:$' + str(grand_total))
So instead of each input being saved and totaled up, it just overwrites all the previous inputs with the value of the last input entered and adds that up however many times it iterated through the loop. I understand why it overwrites the previous values and it makes perfect sense. I just don't know how to update the list while still outputting the original inputs. Thanks in advance for any help!
You create several dict objects and assign each to grocery_item. Each replaces the last under that name, which is fine because you also append each to grocery_history. However, you never use that list (except to determine how many iterations of the totaling loop to perform); instead, you use grocery_item again, which still has whatever single value you assigned to it last.
Just replace
for items in range(0,len(grocery_history)):
with
for grocery_item in grocery_history:
(You weren’t ever using items anyway.)
The problem isn't where you think it is. The values are being appended correctly to grocery_history. You can check that yourself with print(grocery_history).
The problem is in your for loop. You're reading from grocery_item (ie. the last item entered by the user) instead of from the whole grocery_history list. Replace your for loop with this one:
for i in range(0,len(grocery_history)):
item_total = grocery_history[i]['number'] * grocery_history[i]['price']
grand_total = grand_total + item_total
print(str(grocery_history[i]['number']) + ' ' + str(grocery_history[i]['number']) + ' ' + '#' + ' ' + '$' + str(grocery_history[i]['number']) + ' ' + 'ea' + ' ' + '$' + str(item_total))
item_total == 0
print('Grand total:$' + str(grand_total))

Removing And Re-Inserting Spaces

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

Printing values in multiple arrays coming out a jarbled mess

The values in the arrays are fine. If I print them out separately in a loop they come out as they should, but the moment I put them all together it doesn't print the first two values and jumbles the rest. Here's the print snippet:
print '['
for i in range(1, x):
print '{\"' + fNames[0] + '\":"' + fNames[i] + '\", \"' + lNames[0] + '\":\"' + lNames[i] + '\", \"' + descs[0] + '\":\"' + descs[i] + '\"},\r'
print ']'
Here's what it outputs:
[
"},A really cool guy, "lname":"Bishop", "description
"},A really cool galname":"Patzer", "description
"},A really cool momlname":"Robertson", "description
"},A really cool dadame":"Bishop", "description
"},A really cool doglname":"Bishop", "description
"},A really cool cat"lname":"Jack", "description
]
Notice that it doesn't output fName[0] and fName[i].
If I comment out the end of the print statement like so:
print '['
for i in range(1, x):
print '{\"' + fNames[0] + '\":"' + fNames[i] + '\", \"' + lNames[0] + '\":\"' + lNames[i] + '\", \"' + descs[0] + '\":\"' #+ descs[i] + '\"},'
print ']'
It prints out most of it correctly, besides the 'f' in "fname" and notice that it doesn't print out the last '\":\"' at all either. I've already ran the arrays through the filter() function to strip newlines, and made sure my regex doesn't pick them up. This is how I fill the arrays:
with open(file, "rb") as fin:
for line in fin:
col1Reg = re.search('^(.+?)(?=,)', line)
fNames.append(col1Reg.group(0))
col2Parsed = '(?<=' + fNames[x] + ',)(.*)(?=,)'
col2Reg = re.search(col2Parsed, line)
lNames.append(col2Reg.group(0))
col3Parsed = '(?<=' + lNames[x] + ',)(.*)(?=\n)'
col3Reg = re.search(col3Parsed, line)
descs.append(col3Reg.group(0))
x += 1
What the heck is going on? Everything in the arrays is correct and in the correct position, so why is this happening?
It looks like you are trying to output json. Instead of building a string, why not create a list of dictionaries and dump it to json via something like this:
import json
list1 = []
for x in range(i):
list1.append({
'name': 'value',
})
print json.dumps(list1, indent=4)

Categories

Resources