Formatting the output of a key from a dictionary - python
I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?
for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
output:
Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
Just incase it wasn't clear, I would like the last line of the output to be displayed as:
count_loc(infile) -- 15 lines of code
EDIT
name = re.search(func_pattern, line).groups()
name = str(name)
Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple
I don't have Python 3 so I can't test this, but the output of f_name makes it look like it is a tuple with one element in it. So you would change .format(f_name, f_loc) to .format(f_name[0], f_loc)
EDIT:
In response to your edit, try using .group() instead of .groups()
To elaborate on Peter's answer, It looks to me like you're assigning a one-item tuple as the key of your dictionary. If you're evaluating an expression in parentheses somewhere and using that as the key, be sure you don't have a stray comma in there.
Looking at your further edited answer, it's indeed because you're using the groups() method of your regex match. That returns a tuple of (the entire matched section + all the matched groups), and since you have no groups, you want the entire thing. group() with no parameters will give you that.
I expect you have a problem with your parsing code. The lines as written should work as expected.
Since the key is some type of tuple, you may want to join the different elements before printing. We can't really tell what the significance of the key is from the snippet shown.
So you could do something like such:
.format(", ".join(f_name), f_loc)
Related
How can I use user input to choose a parameter name and an attribute name?
I'm using a library called unit-convert. The interface looks like this: # Bytes to terabytes >>> UnitConvert(b=19849347813875).tb Suppose I have strings taken from user input (omitting the input code) like so: input_value_unit = 'b' output_value_unit = 'tb' How can I substitute these into the call? I tried using UnitConvert(input_value_unit=user_input_value).output_value_unit, but this doesn't use the string values.
Code like function(x=1) doesn't care if there's a variable named x naming a string; the x literally means x, not the x variable. Similarly for attributes: x.y doesn't care if there is a y variable naming a string; it will just get the y attribute of x. However, we can use strings to specify both of these things "dynamically". To replace the b in the example, we need to use a string as a keyword argument name. We can do this by making a dictionary for the keyword arguments, and then using ** to pass them. With a literal string, that looks like: UnitConvert(**{'b': ...}). To replace the tb, we need to use a string as an attribute name. We can do this by using the built-in getattr to look up an attribute name dynamically. With a literal string, that looks like: getattr(UnitConvert(...), 'tb'). These transformations let us use a literal string instead of an identifier name. Putting it together: # suppose we have read these from user input: input_value_unit = 'b' output_value_unit = 'tb' input_amount = 19849347813875 # then we use them with the library: getattr(UnitConvert(**{input_value_unit: input_amount}), output_value_unit)
Edit again - perhaps I still misunderstand. You're using an existing module that you downloaded? Now that your code has been pared back to look nothing like the original, my first answer no longer applies. I'll leave it below the underline because you should still be aware. Usually in your situation the second unit would be passed as a second parameter to the function. Then the function can do the appropriate conversion. UnitConvert(user_input_value, output_value_unit) There's an alternative that looks a little closer to what you had in mind. If your function returns a dictionary with all the possible conversions, you can select the one you need. UnitConvert(user_input_value)[output_value_unit] The old irrelevant answer. Your statement: if user_input_convert == ["kilometres", "miles", "nanometres", "metres"]: is comparing a single string to a list of strings. They will never be equal. What you probably want is: if user_input_convert in ["kilometres", "miles", "nanometres", "metres"]: That checks to see if your string is equal to one of the strings in the list.
How to avoid the last comma while writing an integer array into a text file in python
I need to write an array of integers into a text file, but the formatted solution is adding the comma after each item and I'd like to avoid the last one. The code looks like this: with open(name, 'a+') as f: line = ['FOO ', description, '|Bar|'] f.writelines(line) f.writelines("%d," % item for item in values) f.writelines('\n') Each line starts with a small description of what the array to follow contains, and then a list of integers. New lines are added in the loop as they become available. The output I get looks something like this: FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736, And I would like to have it look like this, without the last comma: FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736 I was unable to find a solution that would work with the writelines() and I need to avoid lengthy processing in additional loops.
Use join: f.writelines(",".join(map(str,values))) Note that values is first mapped to a list of strings, instead of numbers, with map.
You can slice it with using below example. It will always delete last character. line = ['FOO ', description, '|Bar|'] line = line[:-1] f.writelines(line)
Slicing is the best approach and works well for every situation atleast in your case. f.writelines(line[:-1])
You can use print function here. print(*values,sep=',',file=f) If you are using python2 please import print function. from __future__ import print_function
What is this code: %(var)s ? Python maybe?
There is an option on the backend of a website that I use that allows me to customize the data sent in a CSV file when an order has been placed for a product. There are two columns, the left column is where you assign the header and the right column is where you input the variable. The syntax for the existing variables is similar to %(order.random_variable)s or %(item.random_variable)s This looks similar to the string placeholder %s in Python and I'm fairly confident that it is related, if not the same, but I don't quite understand the syntax. Could someone please elaborate on the purpose of this code? Oh, and for the record, I don't plan on going in and changing variables around right away. Just looking for a good jumping off point for my research into this.
That is similar to %s. The part inside the parenthesis is optional. The only difference is that, for the first one, your values must be a tuple with exactly the number of items specified by the format string, and for the 2nd one, it must be a single mapping object (for example, a dictionary) It's clearly listed in String formatting documentation: - A conversion specifier contains two or more characters and has the following components, which must occur in this order: The '%' character, which marks the start of the specifier. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)). .. and there are some more Also: - When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping An example from the docs: - >>> print '%(language)s has %(number)03d quote types.' % \ ... {"language": "Python", "number": 2} Python has 002 quote types. So, the text inside the () after % and before s is a key in the dictionary.
Yes, this is similar to %s. The part inside the () is referencing a key of a python dict. For example: mydict = {'yay':'boo'} print '%(yay)s'%mydict # boo
String Delimiter in Python
I want to do split a string using "},{" as the delimiter. I have tried various things but none of them work. string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 " Split it into something like this: 2,1,6,4,5,1 8,1,4,9,6,6,7,0 6,1,2,3,9 2,3,5,4,3 string.split("},{") works at the Python console but if I write a Python script in which do this operation it does not work.
You need to assign the result of string.split("},{") to a new string. For example: string2 = string.split("},{") I think that is the reason you think it works at the console but not in scripts. In the console it just prints out the return value, but in the script you want to make sure you use the returned value.
You need to return the string back to the caller. Assigning to the string parameter doesn't change the caller's variable, so those changes are lost. def convert2list(string): string = string.strip() string = string[2:len(string)-2].split("},{") # Return to caller. return string # Grab return value. converted = convert2list("{1,2},{3,4}")
You could do it in steps: Split at commas to get "{...}" strings. Remove leading and trailing curly braces. It might not be the most Pythonic or efficient, but it's general and doable.
I was taking the input from the console in the form of arguments to the script.... So when I was taking the input as {{2,4,5},{1,9,4,8,6,6,7},{1,2,3},{2,3}} it was not coming properly in the arg[1] .. so the split was basically splitting on an empty string ...
If I run the below code from a script file (in Python 2.7): string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 " print string.split("},{") Then the output I got is: ['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3 '] And the below code also works fine: string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 " def convert2list(string): string=string.strip() string=string[:len(string)].split("},{") print string convert2list(string)
Use This: This will split the string considering },{ as a delimiter and print the list with line breaks. string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3" for each in string.split('},{'): print each Output: 2,1,6,4,5,1 8,1,4,9,6,6,7,0 6,1,2,3,9 2,3,5,4,3 If you want to print the split items in the list only you can use this simple print option. string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3" print string.split('},{') Output: ['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3']
Quite simply ,you have to use split() method ,and "},{" as a delimeter, then print according to arguments (because string will be a list ) , like the following : string.split("},{") for i in range(0,len(string)): print(string[i])
Python, string (consisting of variable and strings, concatenated) used as new variable name?
I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values: toreplacetype = 'type' toreplace_indx = 5 replacement_string = 'list'+toreplacetype[toreplace_indx] so... I am trying to make the string on the last line equal to the actual variable name: replacement_string = listtype[5] Any advice on how to do this is appreciated EDIT: To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
This is not recommended. Use a dict instead. vars['list%s' % toreplacetype][5] = ...
Hrm... globals()['list%s'% toreplacetype][toreplace_indx]
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']' will yield listtype[5] when you print it. You need to basically break it into 5 parts: 1 string variable, 3 strings and an int casted to a string. I think this is what you are asking?