I'm coming from a c# background, and I do this:
Console.Write("some text" + integerValue);
So the integer automatically gets converted to a string and it outputs.
In python I get an error when I do:
print 'hello' + 10
Do I have to convert to string everytime?
How would I do this in python?
String.Format("www.someurl.com/{0}/blah.html", 100);
I'm beginning to really like python, thanks for all your help!
From Python 2.6:
>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'
To support older environments, the % operator has a similar role:
>>> "www.someurl.com/%d/blah.html" % 100
'www.someurl.com/100/blah.html'
If you would like to support named arguments, then you can can pass a dict.
>>> url_args = {'num' : 100 }
>>> "www.someurl.com/%(num)d/blah.html" % url_args
'www.someurl.com/100/blah.html'
In general, when types need to be mixed, I recommend string formatting:
>>> '%d: %s' % (1, 'string formatting',)
'1: string formatting'
String formatting coerces objects into strings by using their __str__ methods.[*] There is much more detailed documentation available on Python string formatting in the docs. This behaviour is different in Python 3+, as all strings are unicode.
If you have a list or tuple of strings, the join method is quite convenient. It applies a separator between all elements of the iterable.
>>> ' '.join(['2:', 'list', 'of', 'strings'])
'2: list of strings'
If you are ever in an environment where you need to support a legacy environment, (e.g. Python <2.5), you should generally avoid string concatenation. See the article referenced in the comments.
[*] Unicode strings use the __unicode__ method.
>>> u'3: %s' % ':)'
u'3: :)'
>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'
you can skip 0 in python 2.7 or 3.1.
Additionally to string formatting, you can always print like this:
print "hello", 10
Works since those are separate arguments and print converts non-string arguments to strings (and inserts a space in between).
For string formatting that includes different types of values, use the % to insert the value into a string:
>>> intvalu = 10
>>> print "hello %i"%intvalu
hello 10
>>>
so in your example:
>>>print "www.someurl.com/%i/blah.html"%100
www.someurl.com/100/blah.html
In this example I'm using %i as the stand-in. This changes depending on what variable type you need to use. %s would be for strings. There is a list here on the python docs website.
Related
I'm quite new to python, so forgive me if this is a silly question. I know how to use the modulo in strings in this fashion
Me = "I'm %s and I like to %s" % ('Mike', 'code')
However, through my searching I haven't found an answer to whether or not it's possible to hardcode modulos into a string, then take advantage of it later.
Example:
REPO_MENU = {'Issues':Api.github/repo/%s/branch/%s/issues,
'Pull Requests':'Api.github/repo/%s/branch/%s/pull_requests',
'Commits':'Api.github/repo/%s/branch/%s/commits'
'<FILTER>: Branch':'Api.github/repo/%s/branch/%s'
}
for key, value in REPO_MENU.items():
Print value % ('Beta', 'master')
Will that format work? Is it good practice to use this method? I feel it could be beneficial in a lot of situations.
This does work. You can also use the format function, which works well. For example:
menu1 = {'start':'hello_{0}_{1}',
'end':'goodbye_{0}_{1}'}
menu2 = {'start':'hello_%s_%s',
'end':'goodbye_%s_%s'}
for key, value in menu1.items():
print value.format('john','smith')
for key, value in menu2.items():
print value %('john','smith')
% is an operator like any other; when its left-hand operand is a string, it attempts to replace various placeholders with values from its right-hand operand. It doesn't matter if the left-hand operand is a string literal or a more complex expression, as long as it evaluates to a string.
As the other answers have noted, you can definitely perform the string-modulo operation multiple times on the same string. However, if you are using Python 3.6 (and if you can, you definitely SHOULD!), I suggest that you use fstrings rather than the string-modulo or .format. They are faster, easier to read, and very convenient:
A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
So the f-string is also portable, just like the other formatting options.
E.g.:
>>> value = f'A {flower.lower()} by any name would smell as sweet.'
>>> flower = 'ROSE'
>>> print(value)
A rose by any name would smell as sweet.
>>> flower = 'Petunia'
>>> print(value)
A petunia by any name would smell as sweet.
>>> flower = 'Ferrari'
>>> print(value)
A ferrari by any name would smell as sweet.
You can add this at the top of any module using the f-string as a helpful alert for other users (or future-you):
try:
eval(f'')
except SyntaxError:
print('Python 3.6+ required.')`.
raise
When converting an object to a string in python, I saw two different idioms:
A: mystring = str(obj)
B: mystring = "%s" % obj
Is there a difference between those two? (Reading the Python docs, I would suspect no, because the latter case would implicitly call str(obj) to convert obj to a string.
If yes, when should I use which?
If no, which one should I prefer in "good" python code? (From the python philosophy "explicit over implicit", A would be considered the better one?)
The second version does more work.
The %s operator calls str() on the value it interpolates, but it also has to parse the template string first to find the placeholder in the first place.
Unless your template string contains more text, there is no point in asking Python to spend more cycles on the "%s" % obj expression.
However, paradoxically, the str() conversion is, in practice, slower as looking up the name str() and pushing the stack to call the function takes more time than the string parsing:
>>> from timeit import timeit
>>> timeit('str(obj)', 'obj = 4.524')
0.32349491119384766
>>> timeit('"%s" % obj', 'obj = 4.524')
0.27424097061157227
You can recover most of that difference by binding str to a local name first:
>>> timeit('_str(obj)', 'obj = 4.524; _str = str')
0.28351712226867676
To most Python developers, using the string templating option is going to be confusing as str() is far more straightforward. Stick to the function unless you have a critical section that does a lot of string conversions.
I had to rewrite my python script from python 3 to python2 and after that I got problem parsing special characters with ElementTree.
This is a piece of my xml:
<account number="89890000" type="Kostnad" taxCode="597" vatCode="">Avsättning egenavgifter</account>
This is the ouput when I parse this row:
('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avs\xc3\xa4ttning egenavgifter')
So it seems to be a problem with the character "ä".
This is how i do it in the code:
sys.setdefaultencoding( "UTF-8" )
xmltree = ET()
xmltree.parse("xxxx.xml")
printAccountPlan(xmltree)
def printAccountPlan(xmltree):
print("account:",str(i.attrib['number']), "AccountType:",str(i.attrib['type']),"Name:",str(i.text))
Anyone have an ide to get the ElementTree parse the charracter "ä", so the result will be like this:
('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avsättning egenavgifter')
You're running into two separate differences between Python 2 and Python 3 at the same time, which is why you're getting unexpected results.
The first difference is one you're probably already aware of: Python's print statement in version 2 became a print function in version 3. That change is creating a special circumstance in your case, which I'll get to a little later. But briefly, this is the difference in how 'print' works:
In Python 3:
>>> # Two arguments 'Hi' and 'there' get passed to the function 'print'.
>>> # They are concatenated with a space separator and printed.
>>> print('Hi', 'there')
>>> Hi there
In Python 2:
>>> # 'print' is a statement which doesn't need parenthesis.
>>> # The parenthesis instead create a tuple containing two elements
>>> # 'Hi' and 'there'. This tuple is then printed.
>>> print('Hi', 'there')
>>> ('Hi', 'there')
The second problem in your case is that tuples print themselves by calling repr() on each of their elements. In Python 3, repr() displays unicode as you want. But in Python 2, repr() uses escape characters for any byte values which fall outside the printable ASCII range (e.g., larger than 127). This is why you're seeing them.
You may decide to resolve this issue, or not, depending on what you're goal is with your code. The representation of a tuple in Python 2 uses escape characters because it's not designed to be displayed to an end-user. It's more for your internal convenience as a developer, for troubleshooting and similar tasks. If you're simply printing it for yourself, then you may not need to change a thing because Python is showing you that the encoded bytes for that non-ASCII character are correctly there in your string. If you do want to display something to the end-user which has the format of how tuples look, then one way to do it (which retains correct printing of unicode) is to manually create the formatting, like this:
def printAccountPlan(xmltree):
data = (i.attrib['number'], i.attrib['type'], i.text)
print "('account:', '%s', 'AccountType:', '%s', 'Name:', '%s')" % data
# Produces this:
# ('account:', '89890000', 'AccountType:', 'Kostnad', 'Name:', 'Avsättning egenavgifter')
I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:
I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.
I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.
Solution:
Here's how I decided to do it:
from string import Template
message = 'You replied to $percentageReplied of your message. ' +
'You earned $moneyMade.'
template = Template(message)
print template.safe_substitute(
percentageReplied = '15%',
moneyMade = '$20')
Here are the most common ways to do it:
>>> import string
>>> t = string.Template("Hello my name is $name")
>>> print t.substitute(name='Guido')
Hello my name is Guido
>>> t = "Hello my name is %(name)s"
>>> print t % dict(name='Tim')
Hello my name is Tim
>>> t = "Hello my name is {name}"
>>> print t.format(name='Barry')
Hello my name is Barry
The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.
The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.
The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the % operator, or better yet, the newer and recommended str.format().
Example:
a = "Hello my name is {name}"
result = a.format(name=b)
Or more simply
result = "Hello my name is {name}".format(name=b)
You can also use positional arguments:
result = "Hello my name is {}, says {}".format(name, speaker)
Or with explicit indexes:
result = "Hello my name is {0}, says {1}".format(name, speaker)
Which allows you to change the ordering of the fields in the string without changing the call to format():
result = "{1} says: 'Hello my name is {0}'".format(name, speaker)
Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.
You could also use the str.replace() function, or regular expressions (from the re module) if the replacements are more complicated.
Checkout the replace() function in python. Here is a link:
http://www.tutorialspoint.com/python/string_replace.htm
This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
For every word "is", it would replace it with the word "was".
Actually this is already implemented in the module string.Template.
You can do something like:
"My name is {name}".format(name="Name")
It's supported natively in python, as you can see here:
http://www.python.org/dev/peps/pep-3101/
You may also use formatting with % but .format() is considered more modern.
>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'
but it also supports some type checking as known from usual % formatting:
>>> '%(x)i' % {'x': 'string'}
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'%(x)i' % {'x': 'string'}
TypeError: %d format: a number is required, not str
I'm just starting to fool around with formatting the output of a print statement.
The examples I've seen have a % after the format list and before the arguments, like this:
>>> a=123
>>> print "%d" % a
123
What is the meaning of the % and more important, why is it necessary?
It's the string formatting operator, it tells Python to look at the string to the left, and build a new string where %-sequences in the string are replaced with formatted versions of the values from the right-hand side of the operator.
It's not "necessary", you can print values directly:
>>> print a
123
But it's nice to have printf()-style formatting available, and this is how you do it in Python.
As pointed out in a comment, note that the string formatting operator is not connected to print in any way, it's an operator just like any other. You can format a value into a string without printing it:
>>> a = 123
>>> padded = "%05d" % a
>>> padded
00123
In python the % operator is implemented by calling the method __mod__ on the left hand argument, falling back to __rmod__ on the right argument if it's not found. So what you have written is equivalent to
a = 123
print "%d".__mod__(a)
Python's string classes simply implement __mod__ to do string formatting.
Also note that this style of string formatting is referred to in the documentation as "old string formatting"; moving forward we should move to the new-style string formatting as described here: http://docs.python.org/library/stdtypes.html#str.format
like:
>>> a=123
>>> print "{0}".format(a)
123
See Format String Syntax for a description of the various
formatting options that can be specified in format strings.
This method of string formatting is the new standard in Python 3.0,
and should be preferred to the % formatting described in String
Formatting Operations in new code.