It's just a curiosity about python. Is there a way to write anything in python files without getting any error and without using comments? It could be a macro / pre processor word / python option to ignore the lines.
For instance:
#!/usr/bin/python
# coding: utf-8
I am writing anything I want here!
def func1(number):
print(number)
func1(3)
and the result wouldn't trigger any error, printing the number 3.
A similar C++ question: Force the compiler to ignore some lines in the program
You could use comments and possibly add a special character outside of the comments if your goal is to apply a custom pre-processor. This would be similar to what the #! commands at the top of your file.
For example, in the following, I just used M: as the special prefix:
#!/usr/bin/python
# coding: utf-8
# M: I am writing anything I want here!
def func1(number):
print(number)
func1(3)
Without comments:
Without comments, you could surround with quotes and assign to a variable:
tmp = "I am writing anything I want here!"
As such:
#!/usr/bin/python
# coding: utf-8
tmp = "I am writing anything I want here!"
def func1(number):
print(number)
func1(3)
With comments
You can comment it out as such:
1. Multi-line comments/strings
#!/usr/bin/python
# coding: utf-8
"""I am writing anything I want here!
Yep, literally anything!
def func1(number):
print(number)
func1(3)
2. Single-line comments
#!/usr/bin/python
# coding: utf-8
#I am writing anything I want here!
def func1(number):
print(number)
func1(3)
The easiest way to do this, although it's technically not Pythonic and should not be left in the final draft as it creates an unused string, is with triple quotes on each side. It's the simplest way to toggle medium-large portions of code. Something like:
x = 5
""" DEBUG:
x += 5
x *= 5 * 5
x = x % 3
x -= 2
"""
print x
If it's one or two lines, you can always use normal comments,
#like this
For your code, you'd want:
#!/usr/bin/python
# coding: utf-8
"""
I am writing anything I want here!
"""
def func1(number):
print(number)
func1(3)
I just found something that I was looking for.
The aswer to my question is available here:
Conditional compilation in Python
https://code.google.com/p/pypreprocessor/
Related
I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)
So I am working with django and an external List of names and values. With a custom template tag I am trying to display some values in my html template.
Here is a example of what the list could look like:
names.txt
hello 4343.5
bye 43233.4
Hëllo 554.3
whatever 4343.8
My template tag looks like this (simplified names of variables):
# -*- coding: utf-8 -*-
from django import template
register = template.Library()
#register.filter(name='operation_name')
def operation_name(member):
with open('/pathtofile/member.txt','r') as f:
for line in f:
if member.member_name in line:
number = float(line.split()[1])
if number is not member.member_number:
member.member_number = number
member.save()
return member.member_number
return 'Not in List'
It works fine for entries without specials char. But it stops when a name in member.member_names has special chars. So if member.member_names would be Hëllo the entire script just stops. I can't return anything. This is driving me crazy. Even the names without special chars won't be displayed after any name with special chars occurred.
I appreciate any help, thanks in advance.
EDIT:
So this did the trick:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
But I don't know if this is a good solution.
This may help you try to compare both to unicode:-
if (member.member_name).decode('latin1') in (line).decode('latin1'):
number = float(line.split()[1])
if number is not member.member_number:
member.member_number = number
member.save()
I am using a dictionary to store some character pairs in Python (I am replacing umlaut characters). Here is what it looks like:
umlautdict={
'ae': 'ä',
'ue': 'ü',
'oe': 'ö'
}
Then I run my inputwords through it like so:
for item in umlautdict.keys():
outputword=inputword.replace(item,umlautdict[item])
But this does not do anything (no replacement happens). When I printed out my umlautdict, I saw that it looks like this:
{'ue': '\xfc', 'oe': '\xf6', 'ae': '\xc3\xa4'}
Of course that is not what I want; however, trying things like unicode() (--> Error) or pre-fixing u did not improve things.
If I type the 'ä' or 'ö' into the replace() command by hand, everything works just fine. I also changed the settings in my script (working in TextWrangler) to # -*- coding: utf-8 -*- as it would net even let me execute the script containing umlauts without it.
So I don't get...
Why does this happen? Why and when do the umlauts change from "good
to evil" when I store them in the dictionary?
How do I fix it?
Also, if anyone knows: what is a good resource to learn about
encoding in Python? I have issues all the time and so many things
don't make sense to me / I can't wrap my head around.
I'm working on a Mac in Python 2.7.10. Thanks for your help!
Converting to Unicode is done by decoding your string (assuming you're getting bytes):
data = "haer ueber loess"
word = data.decode('utf-8') # actual encoding depends on your data
Define your dict with unicode strings as well:
umlautdict={
u'ae': u'ä',
u'ue': u'ü',
u'oe': u'ö'
}
and finally print umlautdict will print out some representation of that dict, usually involving escapes. That's normal, you don't have to worry about that.
Declare your coding.
Use raw format for the special characters.
Iterate properly on your string: keep the changes from each loop iteration as you head to the next.
Here's code to get the job done:
\# -*- coding: utf-8 -*-
umlautdict = {
'ae': r'ä',
'ue': r'ü',
'oe': r'ö'
}
print umlautdict
inputword = "haer ueber loess"
for item in umlautdict.keys():
inputword = inputword.replace(item, umlautdict[item])
print inputword
Output:
{'ue': '\xc3\xbc', 'oe': '\xc3\xb6', 'ae': '\xc3\xa4'}
här über löss
So I am working with a CSV that has a many to one relationship and I have 2 problems I need assistance in solving. The first is that I have the string set up like
thisismystr=thisisanemail#addy.com,blah,blah,blah, startnewCSVcol
So I need to split the string twice, once on = and once on , as I am basically attempting to get the portion that is an e-mail address (thisisanemail#addy.com) so far I have figured out how to split the string on the = using something like this:
str = thisismystr=thisisanemail#addy.com,blah,blah,blah
print str.split("=")
Which returns this "thisisanemail#addy.com,blah,blah,blah"... however this leaves the ,blah,blah,blah portion to be removed... after a bit of research I am stumped as nothing explains how to remove from the middle, just the 1st part or the last part. Does anyone know how to do this?
For the 2nd part I need to do this from multiple line, so this is more of an advice question... is it best to plug this into a variable and loop through like (i = 1 for i, #endofCSV do splitcmd) or is there a more efficient manner to do this? I am more familiar with LUA and I am learning that the more I work with python the more it differs from LUA.
Please help. Thanks!
Does this solve your problem?
#!/usr/bin/env python
#-*- coding:utf-8 -*-
myString = 'thisismystr=thisisanemail#addy.com,blah,blah,blah'
a = myString.split('=')
b = []
for i in a:
b.extend(i.split(','))
print b
I believe you want the email out of strings in this format: 'thisismystr=thisisanemail#addy.com,blah,blah,blah'
This is how you would do that:
str = 'thisismystr=thisisanemail#addy.com,blah,blah,blah'
email = str.split('=')[1].split(',')[0]
print email
I get a word from a form, and to slugify it I want to differentiate it.
Using django's slugify if I get the word 'Ñandu', the slug becomes 'nandu'. And if I get the word 'Nandu' the slug also becomes 'nandu'.
So I decided that if the word starts with 'Ñ' the slug will become 'word_ene'.
The problem is I can't find a way to check if the first character from the input is really a 'ñ' (or 'ñ').
I have tried both self.palabra[0]==u"ñ" and self.palabra[0]=="ñ" with and without encoding palabra before. But I can't get to work.
Thanks in advance.
This works for me:
>>> str = u"Ñandu"
>>> str[0] == u"\xd1"
True
>>> if str[0] == u"\xd1": print "Begins with \xd1!"
Begins with Ñ!
Watch out for case; lower case ñ is encoded as u"\xf1".
If you type things like u"ñ" directly in the code, then you have to remember about putting sth like (with your coding of choice of course):
# -*- coding: utf8 -*-
at the top of your .py file, otherwise Python doesn't know what to do.
http://www.python.org/dev/peps/pep-0263/