How do I print punctuation right after a variable? Python - python

s = "A Colon is beside me"
print s,":"
I should get
A Colon is beside me :
But I wanna get
>>>A Colon is beside me:
How?

Concatenate the strings:
print s + ':'
or use string formatting:
print '{0}:'.format(s)
On python 3, the print() function can also be told to use an empty separator between multiple arguments, instead of a space:
print(s, ':', sep='')

This definatly works. (I am new to the site and I have put normal text not code!?)
print "%s:" % s
The %s means insert a variable here and the second s means insert the specific variable 's

This is for summarization purpose.
There are four ways to print statement:
s = "A Colon is beside me"
Data Type Parsing Mode:
print("%s:" %s)
Variables Concatenation Mode:
print(s+":")
format() method:
print("{}:".format(s))
Using Built-in function:
print(s,':',sep='')

Related

In python how to replace a character in a string

import re
n=input("Enter a String:")
# Replace the String based on the pattern
replacedText = re.sub('[%]+','$', n,1)
# Print the replaced string
print("Replaced Text:",replacedText)
input I have given is:
ro%hi%
Output:
ro$hi%
I want to change the second % in the String with empty space(''). Is it possible. For that what changes can I do in my code.
Here is an arguably dumb solution, but it seems to do what you need. Would be good if you want to avoid regex and don't mind two function calls (i.e., performance in that sense isn't critical).
input_text = "ro%hi%"
output_text = input_text.replace("%", "$", 1).replace("%", "", 1)
print(output_text)
Terminal output:
$ python exp.py
ro$hi
use replace() function.
Specify how many occurances you need to replace at the end.
x = "ro%hi%"
print(x.replace("%", "$", 1)
You can use .replace("%", "$", 1) which will replace first % with $ then apply another .replace("%", "") to replace second % with ''.
n=input("Enter a String:")
# Print the replaced string
# This will replace the first % with $ and replace second % with ''
print("Replaced Text:",n.replace('%','$',1).replace('%', '', 1))
# If there are only two % in your input then you can use
# print("Replaced Text:",n.replace('%','$',1).rstrip('%')
Output:
ro$hi
You can just do
n.replace('%','')

What do empty curly braces mean in a string?

So I have been browsing through online sites to read a file line by line and I come to this part of this code:
print("Line {}: {}".format(linecount, line))
I am quite confused as to what is happening here. I know that it is printing something, but it shows:
"Line{}"
I do not understand what this means. I know that you could write this:
foo = "hi"
print(f"{foo} bob")
But I don't get why there are empty brackets.
Empty braces are equivalent to numeric braces numbered from 0:
>>> '{}: {}'.format(1,2)
'1: 2'
>>> '{0}: {1}'.format(1,2)
'1: 2'
Just a shortcut.
But if you use numerals you can control the order:
>>> '{1}: {0}'.format(1,2)
'2: 1'
Or the number of times something is used:
>>> '{0}: {0}, {1}: {1}'.format(1,2)
'1: 1, 2: 2'
Which you cannot do with empty braces.
Doing "My {} string is {}".format('formatted', 'awesome') just fills in the curly braces with the args you provide in the format function in the order you enter the arguments.
So the first {} in the above string would get 'formatted' and the second in that case would get 'awesome'.
It's an older version of formatting strings than f strings (which I'm glad I started learning Python when these already came out), but you can equally write something like this similar to f-strings:
>>> template = 'I love {item}. It makes me {emotion}'
>>>
>>> my_sentence = template.format(item='fire', emotion='calm')
>>> print(my_sentence)
I love fire. It makes me calm.
This is a different way to interpolate strings in Python.
Docs: https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting
The usage of string interpolations like this f'Results of the {year} {event}' came in Python 3.6.

The difference between these 2 strings?

I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with Learn Python The Hard Way. In Exercise 6, I came across a problem where I was using the %r string formatting operation and it was resulting in two different strings. When I printed one string, I got the string with the single quotes (' '). With another I was getting double quotes (" ").
Here is the code:
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print "I said: %r." % x
print "I also said: %r." % y
The result from the first print statement:
I said: 'There are 10 types of people.'.
The result from the second print statement:
I also said: "Those who know binary and those who don't.".
I want to know why one of the statements had a result with the single quotes (' ') and another with (" ").
]
P.S. I am using Python 2.7.
%r is getting the repr version of the string:
>>> x = 'here'
>>> print repr(x)
'here'
You see, single quotes are what are normally used. In the case of y, however, you have a single quote (apostrophe) inside the string. Well, the repr of an object is often defined so that evaluating it as code is equal to the original object. If Python were to use single quotes, that would result in an error:
>>> x = 'those who don't'
File "<stdin>", line 1
x = 'those who don't'
^
SyntaxError: invalid syntax
so it uses double quotes instead.
Notice this line -> do_not = "don't". There is a single quote in this string, that means that single quote has to be escaped; otherwise where would the interpreter know where a string began and ended? Python knows to use "" to represent this string literal.
If we remove the ', then we can expect a single quote surrounding the string:
do_not = "dont"
>>> I also said: 'Those who know binary and those who dont.'.
Single vs. double quotes in python.

How to print a variable and a string in Python without a space between

My code is the following:
a = 60
print(a, ": string of text")
this prints "60 : string of text"
I would like it to print "60: String of text" without the space after the 60 if that makes sense
any ideas?
There are several ways to remove the space delimiter. Fortunately print() only inserts a space between fields by default. From the print() doc:
"sep: string inserted between values, default a space."
So my preferred way would be to use an empty string:
print(a, ": string of text", sep="")
print("{}: string of text".format(a))
if you use print(... , ... , ...) the , will always insert a space.
you can bypass that if you just concatenate them with
print(str(a) + ": string of text")
(the str(..) is needed because a is a number)
or you can use placeholders like so
print("%d: string of text" % a)
.. where %d stands for a digit. if you want a string, use %s
hope this helps :)

Python printing string.split without square braces

I have
cmd=arg[3:]
which gives for e.g.
['file python parameter1=5 parameter2=456 ']
When I am printing I want to print in the format - python file parameters..
I tried
print "%s %s %s" % (string.split(cmd[0])[1],string.split(cmd[0])[0],string.split(cmd[0])[2:])
which gives
python file ['parameter1=5 parameter2=456 ']
How can i get the parameters part printed without the square braces or the quotes?
Thanks.
For the last part how can I print
You are asking Python to turn a list into a string. This is why you are seeing the brackets and quotes. All you need to do is use join to make it a string again.
" ".join(string.split(cmd[0])[2:])
or if you really prefer the string module
string.join(" ", string.split(cmd[0])[2:])
I would prefer to see the code written like this if I were doing a code review:
fname, interp, args = cmd[0].split(" ", 2)
print "%s %s %s" % (interp, fname, args)
Use the format method in preference to %-style string formatting.
print "{0[1]} {0[0]} {0[2]}".format(cmd[0].split(None, 2))
You could try something like that:
' '.join(cmd[0].split()[2:])
instead of:
string.split(cmd[0])[2:]
Also, I would recommend you to use an intermediate variable to avoid to do the same split 3 times... Or even better :
print ' '.join(cmd[0].split(' ', 2))
or actually simply:
print cmd[0]
But I guess you don't want to only print it...

Categories