I am using Python 2.x, and trying to understand the logic of string formatting using named arguments. I understand:
"{} and {}".format(10, 20) prints '10 and 20'.
In like manner '{name} and {state}'.format(name='X', state='Y') prints X and Y
But why this isn't working?
my_string = "Hi! My name is {name}. I live in {state}"
my_string.format(name='Xi', state='Xo')
print(my_string)
It prints "Hi! My name is {name}. I live in {state}"
format doesn't alter the string you call it on; it returns a new string. If you do
my_string = "Hi! My name is {name}. I live in {state}"
new_string = my_string.format(name='Xi', state='Xo')
print(new_string)
then you should see the expected result.
Related
n=str(input("Enter your name"))
a=str(input("Where do you live?"))
print("Hello",n,"How is the weather at",a,"?")
How to Remove space between {a & ?} in the print statement?
An f-string will give you better control over the exact formatting:
print(f"Hello {n}. How is the weather at {a}?")
Commas in python add a space in the output.
No need to use str as inputs in python are already treated as strings.
You can use this:
n = input("Enter your name")
a = input("Where do you live?")
print("Hello",n,"How is the weather at",a+"?")
This concatenates the two strings.
OR
n = input("Enter your name")
a = input("Where do you live?")
print(f"Hello {n}! How is the weather at {a}?")
This is called f-strings. It formats the string so you can put the value of a variable in the output.
You can simply do it by using end inside the print
by default its value is \n and if you set it an empty string ''
it won't add anything(or any space).
after printing a and the ? will print exactly after that.
so you can write the code below:
print("Hello",n,"How is the weather at",a, end='')
print("?")
could anyone explain how format() works in python? where to use it, and how to use it?. I am not getting even I about this keyword
You can regarding it as a kind of string replacement.
{} part in the string -> string.format() content
Definition: https://www.w3schools.com/python/ref_string_format.asp
A pratical example can be like this:
base_url = 'www.xxxx.com/test?page={}'
for i in range(10):
url = base_url.format(i)
do sth
The format() method formats the specified value(s) and insert them inside the string's placeholder.
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
Here fname will be replaced by John and age will be replaced by 36, if you print txt1.
Alternatively you can use f strings .
eg:
fname= "John"
age= 36
print(f"My name is {fname}, I'm {age}")
Even it will print the same output.
Format is often applied as a str-type method: txt.format(...), where type(txt)='str'.
This function is used to insert values inside string's placeholders. Placeholders are curly brackets {} placed inside a string and the format() method returns a formatted string with the values plugged into the string.
This function also enables formatting different type of variables in different ways. E.g. float with value 0.0001 can be represented in floating point representation: 0.0001 or scientific representation 1e-4 using different specifires.
Usage:
txt = "My name is {name}. I'm {age} years old."
print(txt.format(name="Dan", age=32))
Will output: 'My name is Dan. I'm 32 years old.'
You can use positional arguments as well:
txt = "My name is {}. I'm {} years old."
print(txt.format("Dan", 32))
Where the values are taken by their order.
This will output the same result.
To format with different formatting you can use specifiers:
txt = "Decimal numbers: {number:d}"
print(txt.format(number=8340))
txt = "Fix point numbers: {number:.2f}"
print(txt.format(number=3.1415))
There are other specifiers that have other formatting behavior like centering some value to match some desired width:
txt = "{center:^20}"
print(txt.format(center='center'))
This will output ' center ' which contains exactly 20 characters.
There are many more formatting options that you can browse here
or in many other rescorces.
My code looks like this:
name = Joe
print "Hello", name, "!"
My output looks like:
Hello Joe !
How do I remove the space between Joe and !?
There are several ways of constructing strings in python. My favorite used to be the format function:
print "Hello {}!".format(name)
You can also concatenate strings using the + operator.
print "Hello " + name + "!"
More information about the format function (and strings in general) can be found here:
https://docs.python.org/2/library/string.html#string.Formatter.format
6 Years Later...
You can now use something called f-Strings if you're using python 3.6 or newer. Just prefix the string with the letter f then insert variable names inside some brackets.
print(f"Hello {name}")
a comma after print will add a blank space.
What you need to do is concatenate the string you want to print; this can be done like this:
name = 'Joe'
print 'Hello ' + name + '!'
Joe must be put between quotes to define it as a string.
>>> print (name)
Joe
>>> print('Hello ', name, '!')
Hello Joe !
>>> print('Hello ', name, '!', sep='')
Hello Joe!
You can also use printf style formatting:
>>> name = 'Joe'
>>> print 'Hello %s !' % name
Hello Joe !
One other solution would be to use the following:
Print 'Hello {} !'.format(name.trim())
This removes all the leading and trailing spaces and special character.
This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 8 years ago.
I have a string that contains a % that I ALSO want to use %s to replace a section of that string with a variable. Something like
name = 'john'
string = 'hello %s! You owe 10%.' % (name)
But when I run it, I get
not enough arguments for format string
I'm pretty sure that means that python thinks I'm trying to insert more than 1 variable into the string but only included the one. How do I overcome this? Thanks!
You can use a % in your string using this syntax, by escaping it with another %:
>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
More about: String Formatting Operations - Python 2.x documentation
As #Burhan added after my post, you can bypass this problem by using the format syntax recommended by Python 3:
>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
In addition to what Maxime posted, you can also do this:
>> name = 'john'
>>> str = 'Hello {}! You owe 10%'.format(name)
>>> str
'Hello john! You owe 10%'
Basicaly I have a user inputted string like:
"hi my name is bob"
what I would like to do is have my program randomly pick a new ending of the string and end it with my specified ending.
For example:
"hi my name DUR."
"hi mDUR."
etc etc
I'm kinda new to python so hopefully there's an easy solution to this hehe
Something like this:
import random
s = "hi my name is bob"
r = random.randint(0, len(s))
print s[:r] + "DUR"
String concatentation is accomplished with +. The [a:b] notation is called a slice. s[:r] returns the first r characters of s.
s[:random.randrange(len(s))] + "DUR"
Not sure why you would want this, but you can do something like the following
import random
user_string = 'hi my name is bob'
my_custom_string = 'DUR'
print ''.join([x[:random.randint(0, len(user_string))], my_custom_string])
You should read the docs for the random module to find out which method you should be using.
just one of the many ways
>>> import random
>>> specified="DUR"
>>> s="hi my name is bob"
>>> s[:s.index(random.choice(s))]+specified
'hi mDUR'
You can use the random module. See an example below:
import random
s = "hi my name is bob"
pos = random.randint(0, len(s))
s = s[:pos] + "DUR"
print s