Printing values in multiple arrays coming out a jarbled mess - python

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)

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.

Parsing a list with hyphens including and extra hyphen at the end

I have a function that takes elements in a list and adds a hyphen between them and it works fine, the issue is when I want to add [" ", " ", " "] as a list it outputs ------ but it should have outputted - - - because there are 3 elements in the list. I can't figure out how to fix this. Any help is appreciated. Thanks in advance.
def printList(myList):
str1 = ' '.join(map(str,myList))
for i in range(0, len(str1), 1):
if (str1[i] == ' '):
str1 = str1.replace(str1[i], '-')
print(str1 + "-")
printList([" ", " ", " "])
You should use join() as this is exactly what it is designed for.
'-'.join([" ", " ", " "])
#' - - '
If you also want to add - to the end, just add it to the output string
'-'.join([" ", " ", " "]) + '- '
#' - - - '
For integer based lists, map your elements to str()
'-'.join(map(str, [1, 2, 3, 4, 5]))
#'1-2-3-4-5'

Python value assignment does not print

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 + '.')

Python regular expression to parse a list into text for a response

When I run the code below I get:
Thank you for joining, ['cars', 'gas', 'jewelry']but['bus', 'join'] are not keywords.
How can I effectively turn the lists in to just strings to be printed? I suspect I may need a regular expression... this time :)
import re
pattern = re.compile('[a-z]+', re.IGNORECASE)
text = "join cars jewelry gas bus"
keywordset = set(('cars', 'jewelry', 'gas', 'food', 'van', 'party', 'shoes'))
words = pattern.findall(text.lower())
notkeywords = list(set(words) - keywordset)
keywords = list(keywordset & set(words))
if notkeywords == ['join']:
print "Thank you for joining keywords " + str(keywords) + "!"
else:
print "Thank you for joining, " + str(keywords) + "but" + str(notkeywords) + " are not keywords."
To convert list to strings use str.join like this
print "Thank you for joining keywords " + ",".join(keywords) + "!"
This if notkeywords == ['join']: is not a way to compare list elements.
>>> mylist = [1,2]
>>> mylist == 1
False
you should in operator to check for equality.
>>> mylist = [1,2]
>>> 1 in mylist
True
Just use someString.join(list):
if notkeywords == ['join']:
print "Thank you for joining keywords " + ", ".join(keywords) + "!"
else:
print "Thank you for joining, " + ", ".join(keywords) + "but" + ", ".join(notkeywords) + " are not keywords."
If I understood your question correctly, you'll want to use the .join() string method to combine the list before printing it.
For example:
', '.join(my_list)
will give you comma separated output. ', ' can be whatever kind of separator you like.

Categories

Resources