This question already has answers here:
Print without space in python 3
(6 answers)
Closed 3 years ago.
I am currently doing a tutorial in repl.it, and have used this website a little bit for web development. I cannot understand how to do this problem, and I think I got everything else right, except that there is a whitespace in the middle of what Python 3 prints out.
The question is:
Given a two-digit integer, swap its digits and print the result.
The code I have written is this:
a = int(input())
b = int(a / 10)
c = int(a % 10)
print(c, b)
When I put the sample input in, 79, it seems to swap correctly, but it leaves a space, of which I know is technically a character and is wrong.
Input: 79
Output: 9 7
Thanks for answering!
The Problem
The comma in the print statement tells python to put a space.
The Solution
You want to put both integers together as strings, so this is your best route:
a = int(input())
b = int(a / 10)
c = int(a % 10)
print("{0}{1}".format(c, b))
Experimenting with the Code
I invite you to try some variations on the format string to understand best how it works.
ex1
print("{0} and {1}".format(7, 9))
# output: 7 and 9
Examine what happens when you change the characters inside the string, or in the format function.
ex2
print("My first name is {0} and {0} likes {1}!".format("Samy", "pie"))
# output: My first name is Samy and Samy likes pie!
I hoping it becomes clear that the format function preforms substitutions in strings.
"{0}" gets replaced with the first argument to the format call.
"{1}" gets replaced with the first argument to the format call.
and so on..
You can have additional arguments:
ex3
print("My favorite numbers are {0}, {1}, {2}, and {3}.".format(9, 23, 45, 97))
# output: My favorite numbers are 9, 23, 45, and 97.
More information
My favorite way to learn python was always trial and error, and experimenting with the code. It has always felt like the language wanted me to do that, but another great way to learn is to read specifications.
Visit the specification of the format function: https://docs.python.org/3.4/library/string.html#format-string-syntax
You will learn everything there is to know about the function.
Most notably,
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order.
Notice that field_name refers to what's on the inside of {}
Related
This question already has answers here:
Dynamically calculated zero padding in format string in python
(2 answers)
How do I pad a string with zeroes?
(19 answers)
Closed 9 months ago.
Sorry if this is a bit of a noob question. But moving on..
Say at the beginning of my code I set a variable, like this:
TestVar = 'A6'
But I later want it to print out as 000000A6
Or say it was
TestVar = 'C30'
I'd want it to print out as 00000C30
Basically always returning it with a length of 8
The reasoning for this is I've made a general script for modding a game, (I can link if asked) and you need to put in certain values which I want to have format automatically for ease of use. For example on running it'll print
Item ID Here:
And if you put in 166 it would convert the decimal number to hex which would be A6, however in order to be usable for all values (not just ones that are 2 digits once converted) I'm trying to make it detect it's length and format it with the 0s before.
Sorry if this doesnt make sense, in a simpler way of saying this, is there a way for it to detect the length of a variable? So for example in pseudo
TestVar = 'C30'
If TestVar length = 3
print('00000'+TestVar)
Print Result: 00000C30
Basically always returning it with a length of 8
That's what format strings do:
>>> print(f"{'C30':>08s}")
00000C30
As a sidenote, to output any number as 8-digit hex:
>>> print(f"{100:>08X}")
00000064
>>> print(f"{1024:>08X}")
00000400
See the documentation:
for f-strings (the f'I am an f-string' syntax);
for formatting syntax (the >08s and >08X thing).
Use string function rjust():
print(test.rjust(8,'0'))
The .zfill string method can be used.
For example:
s = 'C30'
s.zfill(8)
>>> '00000C30'
Try this code
txt = "A6"
x = txt.zfill(8)
print(x)
You can use string.zfill method
for example.
code = '3C0'
filledCode = code.zfill(8)
this method filled with zero the number of digit that you pass like a parameter
try something like this str.rjust() function
i = 1111
pad = '0'
n = 8
x = str(i).rjust(n, pad)
print(x) # 00001111
print(*range(1, int(input())+1), sep='')
This was the code I found in a discussion on hacker rank. But I did not understand it.
Can anyone please explain this?
So, from what I can tell, this is how it works:
int(input())
This takes input from the user.
Next;
range(1,...+1)
This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number.
And then:
print(*...,sep='')
The * sign, from what I can tell, just effectively returns each value in our range one to be printed.
The sep='' just means each value is separated by '' or nothing.
Hope this is useful to you.
[EDIT]
More on star and double star expressions in this post:
What does the star and doublestar operator mean in a function call?
Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:
n = input("Type integer value: ")
try:
[print(x+1,end="") for x in range(int(n))]
except ValueError:
exit("Typed string not number")
I am learning Python and here is an example of some code :
When would you use this :
Y = "Apple"
print "The object is an %s" % Y
And when would you use this?
X = "Grape"
print "The object is an " , X
And why?
The difference goes beyond just convenience and preference. The two methods are two different things.
Let's consider print "The object is an " , X first. The print statement in Python 2 is a bit irregular and unintuitive in its behavior, which is one of the reasons why Python 3 has a print function instead. In Python 2, the statement takes comma-separated expressions, and prints them out one by one, converting them to strings if necessary, and using a few rules to decide whether to put a space before each expression (it puts a space except "(1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement.")
So when you have strings X and Y, and do print X,Y, it prints X and then Y, probably with whitespace in between. If you want to print a bunch of things quickly, this works well. It's to some extent an easy shorthand for combining separate strings as well. It just prints string representations of the expressions you put in, however. Unless you've already converted the objects to the string you want them to be, you don't have any control over what they look like. It is also something that's specific to the print statement.
The % operation for string formatting, on the other hand, is its own thing; you don't need to use it with print. You can also do things like a = "The object is an %s." % X, and it will work as expected, substituting in the X. But that's not all it can do, or it wouldn't be called string formatting. Instead, it allows you to control how things are put into the string, especially for numbers. This makes it more generally useful, even if the usage is a bit opaque, and reading the documentation on it is a good idea. But, as some examples:
In [1]: a = 1507.2515621
In [2]: print "a is: %d" % a # print as a signed integer
a is: 1507
In [3]: print "a is: %f" % a # print as a float, decimal format
a is: 1507.251562
In [4]: print "a is: %10.2E" % a # print as a float in exponential format, with
a is: 1.51E+03
In [5]: print "a is: %x" % a # signed hexadecimal
a is: 5e3
In [6]: print "The object is an %s." % "Apple" # a string using str()
The object is an Apple.
In [7]: print "The object is an %r." % "Apple" # a string using repr()
The object is an 'Apple'.
In [19]: z = {'a': 2, 'b': 3}
In [21]: print "a is %(a)d, and b is %(b)d." % z
a is 2, and b is 3.
You should be aware, however, that % formatting is no longer considered the "correct" way to do string formatting, and it isn't in Python 3 at all. Instead, both Python 2.6 and up, and Python 3 have the .format method on strings, which is less compact, but fits the rest of python much better (% is actually an overloaded modulo operator). As some examples:
In [39]: print "a is: {0}, or {0:g}, or {0:e}, and z is {1:s},\n and a in z is {1[a]}, \
....: but the a variable is {0:,}.".format(a,z)
a is: 1507.2515621, or 1507.25, or 1.507252e+03, and z is {'a': 2, 'b': 3},
and a in z is 2, but the a variable is 1,507.2515621.
This has many options, and I'd highly recommend reading the documentation on it. Unfortunately, it has what I feel are some unfortunate design choices, and the documentation is rather opaque.
A better example of when you would use the first method (percent formatting) would be
Y = 'Apple'
print "The %s tastes sweet." % Y
It allows you to easily insert variables into a string without having to do something like this:
Y = 'Apple'
print "The", Y, " tastes sweet."
So it's personal preference really, but percent formatting allows one to insert variables into a string without concatenation.
The former prints a single, formatted string. The latter prints two things, one after the other, separated by a space. Use string formatting when you want to put together a string, such as for use in a GUI element or as an argument to some processing function. Sending multiple objects to the print statement (or to the print() function in Python 3) is mostly for print debugging (although there's nothing wrong with using it in a command-line program, if the resulting code is as clear as what you'd create with string formatting).
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 1 year ago.
I'm new to Python, so I've been running through my own set of exercises to simply start memorizing basic functions and syntax.
I'm using the PyCharm IDE and Python 3.4. I've run into an issue when running through some basic string and integer concatenation exercises. Each instance below is throwing an unsupported operand type. There are several threads on Stack Overflow that clearly states proper concatenation syntax, but the above error message continues to plague me.
print ("Type string: ") + str(123)
print ("Concatenate strings and ints "), 10
In Python 3+, print is a function, so it must be called with its arguments between parentheses. So looking at your example:
print ("Type string: ") + str(123)
It's actually the same as:
var = print("Type string: ")
var + str(123)
Since print returns nothing (in Python, this means None), this is the equivalent of:
None + str(123)
which evidently will give an error.
That being said about what you tried to do, what you want do to is very easy: pass the print function what you mean to print, which can be done in various ways:
print ("Type string: " + str(123))
# Using format method to generate a string with the desired contents
print ("Type string: {}".format(123))
# Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
print ("Type string:", str(123)) # Notice this will insert a space between the parameters
Note that print is a function in Python 3. In Python 2, your first line would concatenate "Type string: " and "123" and then print them. In Python 3, you are calling the print function with one argument, which returns None, and then add "123" to it. That doesn't make any sense.
The second line doesn't generate an error in Python 2 or 3 (I've tested it with 2.7.7 and 3.2.3). In Python 2, you get
Concatenate strings and ints 10
while in Python 3, your script should only print
Concatenate strings and ints
This is because again, print is a function, and therefore you call it with the argument "Concatenate strings and ints". The , 10 makes your line a tuple of the return value of print, which is None, and 10. Since you don't use that tuple for anything, there is no visible effect.
Try format():
print("Type string: {}".format(123))
print("Concatenate strings and ints {}".format(10))
There is nothing wrong with this:
print ("Type string: ") + str(123)
print is just a function like anything else. And you're calling that function with one argument, "Type string: ", and then trying to add the result (which will be None) to the string '123'. That isn't going to work. If you wanted to add the two strings together, you have to put them into the same expression, inside the parentheses:
print("Type string: " + str(123))
Similarly:
print ("Concatenate strings and ints "), 10
This calls print with one argument, and then makes a tuple of the None returned by print and the number 10. If you want to pass 10 to the print call, it has to go inside the parentheses:
print("Concatenate strings and ints ", 10)
As gitaarik's answer points out, using str.format is more flexible, and avoids the possibility of problems like this. It also gives you code that works exactly the same way in both Python 2.6-2.7 and Python 3.x, which is pretty nice even if you aren't trying to write dual-platform/single-codebase code, because it'll be understandable even to people who only know one or the other.
I think this is a pretty cool way to concatenate a string and an int in Python:
print (f"Type string: {123}")
print (f"Concatenate strings and ints {10}")
You can do it like this:
c = 'Emerson'
d = 32
print("My name is %s and I am %d years old." %(c,d))
Result:
My name is Emerson and I am 32 years old.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is my problem ? I want act inverse number--example : 123 ==>321
def loop(a):
i=0
while(a>=1)
print(a%10)
s=s/10
i=i+1
Your solution has a few problems, aside from the indentation and the missing colon.
First of all your are using print which automatically adds a line break, so that might not be what you want the result to look like. You could store the result in a string which you append the latest character to and then print it once at the end.
Further, you are using a variable s which was never used before. In thise case it should be a as you want to strip off the last digit using an integer division by 10. Note that in this case, this will only work like that in Python 2, as Python 3 will use a float division there (e.g. 15 / 10 == 1.5). You can prevent that by explicitly using the integer division there (this will also make your intend more clear): s = s // 10 (note the two slashes).
Lastly, you are incrementing the variable i without ever using it, so you can just get rid of it.
In the end, it might look like this:
def reverse (a):
rev = ''
while a > 1:
rev += str(a % 10)
a = a // 10
A shorter solution, utilizing the fact that you can just reverse strings:
>>> num = 123
>>> rev = int(str(num)[::-1])
>>> rev
321
If you leave out the int(), you can even keep trailing/leading zeros and get a string instead:
>>> num = 3210
>>> str(num)[::-1]
'0123'
Few issues:
Your indentation does not match. PEP 8 suggests 4 spaces for indentation.
You're missing a colon after while(a>=1)
Although this isn't an issue, you don't need the parentheses in the while loop, it can just be while a >= 1
s = s/10 might not return what you expect. For example, 12/10 == 1 (unless you're dealing with floats here).
This can all be simplified using slicing:
>>> print int(str(123)[::-1])
321
It is important to indent correctly. (And don't mix tabs and spaces.)
def loop(a):
i = 0
while a >= 1:
print(a % 10)
a = a / 10
i = i + 1
You were also missing a colon after the while condition.