How can I add space as parameter in string in python
For example,
If I write:
s="test"
print(f" {s:< 5}{s}")
Then
test test
I want something that
w=5
printf(f" {s:<f'{w}'}{s}")
Try this:
s = "test"
w = 5
print(f" {s:<{w}}{s}")
This should produce the same result as:
print(f" {s:<5}{s}")
If I have well understood, you want to print w spaces.
You could do something like : print(f"{s:<{w}}{s}")
Else, there is also the method ljust :
print(s.ljust(w, " ")+s)
Instead Try This:
print(f"{s:<{w}{s}")
Printf() is nothing in python until you define function named printf() manually. And You can't initialise format specifier inside format specifier.
Related
I'm coming into Python3 after spending time with Ruby, R, and some Java. Immediately I've come across the format() function and I'm a little lost as to what it does. I've read Python | format() function and see that it somehow resembles this in ruby:
my_name = "Melanie"
puts "My name is #{my_name}."
Outputs:
"My name is Melanie."
However, I don't understand why I can't just use a variable as above. I must be very much misunderstanding the usage of the format() function. (I'm a novice, please be gentle.)
So what does format() actually do?
You can definitely use a variable in the string example that you have shown, in the following manner:
my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)
My name is Melanie.
This is the easy way, but not the most elegant.
In the above example, I have used 3 lines and created 2 variables (my_name and Output)
However, I can get the same output using just one line of code and without creating any variables, using format()
print("My name is {}.".format("Melanie"))
My name is Melanie.
Curly braces {} are used as placeholders, and the value we wish to put in the placeholders are passed as parameters into the format function.
If you have more than one placeholder in the string, python will replace the placeholders by values, in order.
Just make sure that the number of values passed as parameters to format(), is equal to the number of placeholders created in the string.
For example:
print("My name is {}, and I am {}.".format("Melanie",26))
My name is Melanie, and I am 26.
There are 3 different ways to specify placeholders and their values:
Type 1:
print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))
Type 2:
print("My name is {0}, and I am {1}.".format("Melanie",26))
Type 3:
print("My name is {}, and I am {}.".format("Melanie",26))
Additionally, by using format() instead of a variable, you can:
Specify the data type, and
Add a formatting type to format the result.
For example:
print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))
Melanie has completed 75.765 percent of task 1.
I have set the data type for the percentage field to be a float, with 3 decimals, and given a character length of 7 to the name, and center-aligned it.
The alignment codes are:
' < ' :left-align text
' ^ ' :center text
' > ' :right-align
The format() method is helpful when you have multiple substitutions and formattings to perform on a string.
The format function is a method for string in python, it is use to add a variable to string. for example:
greetings = 'hello {0}'
visitor = input('please enter your name')
print(greetings.format(visitor))
it can also be use to pad/position string also, thisn actually align the visitor into to the greetings in 10 byte of space
greetings = 'hello {0:^10}'
visitor = input('please enter your name')
print(greetings.format(visitor))
Also, there are two type of format in python 3x: the format expression and the format function.
the format expression is actually this '%'
and many more on 'format'. Maybe you should check on the doc 'format' by typing "help(''.format)"
An example using the format function is this:
name = Arnold
age = 5
print("{ }, { }".format(name, age))
This displays:
Arnold, 5
My code is like this:
main(){
var courselist = ["dart","flutter","swift","R"];
print(courselist[0]);
}
But I want to print my output as like this .. 'dart' and 'R'
How can I print 2 or more values in array concept?
I have tried doing like this:
print(courselist[0],[3]);
print(courselist[0],courselist[3]);
print(courselist[0] & [3]);
My Code:
main(){
var courselist = ["dart","flutter",24,0.45];
print(courselist[0]);
}
Error:
Harish#Harish:~/Desktop/dartfiles/Basics$ dart 01var_datatypes.dart
01var_datatypes.dart:26:20: Error: The method '[]' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named '[]'.
print(courselist[2][0]);
^^
You need to write courselist[i] to print ith index entry of the list. You need to write print(courselist [0], courselist [3]) to print each of the entry. Writing print(courselist [0],[3]) or print(courselist [0]and[3]) will not work. If you have large number of indices to print then you can avoid writing multiple times by iterating over a list:
vals=[0,3]
for val in vals:
print(courselist [val])
You need to use correct PYTHON code for this to work.
If you want to display two variable in fluttet(dart) as you add tag you have can do as mention below.
print('Something ${variable1} ${variable 2} ');
You can also add whatever text you want at anywhere.
Within a quoted string you can build your output by evaluating expressions and variables.
Expressions surround them with ${expr}. Variables just prefix with $. E.g. $varname,
main() {
var courselist = ["dart", "flutter", "swift", "R"];
print("Dart Course: ${courselist[0]}, R Course: ${courselist[3]}");
num grade = 10;
print("Amount $grade");
}
Can anyone help me with the assignment - I have to reverse a string by using def. I am not allowed to use approaches like [::-1] or .reversed...
The following function works, but prints vertically:
def ex1(name):
for x in range(len(name)-1,-1,-1):
print(name[x])
k
r
o
Y
w
e
N
how do I put the letters back into horizontal order?? Anyone? Thanks!
You can use str.join and a list comprehension like so:
>>> def ex1(name):
... return "".join([name[x] for x in range(len(name)-1,-1,-1)])
...
>>> print(ex1('abcd'))
dcba
>>>
Also, notice that I made the function return the string instead of print it. If your teachers want you to use def for this job, then they probably want that too. If not, then you can always replace return with print if you want.
You were very close:
def ex1(name):
reverseName=""
for x in range(len(name)-1,-1,-1):
reverseName+=name[x]
print reverseName
The print statement prints a newline character (a line break) after each line, this is why you get your characters in vertical. The solution is not to print the character in each loop, but to collect them in a string and print the final string at once at the end.
Note that there are more efficient ways of doing this (see the other answers), but it might be the most straightforward way and the closest one to what you have already done.
Here is another way that you can reverse a string.
def ex1(name):
length = len(name)
return "".join([name[length-x-1] for x in range(0, length)])
print ex1("hello world")
name=input("Whats your name ?")
def reversemyname(name):
x=name[::-1]
return x
reversedname=reversemyname(name)
print(reversedname)
print(name[x]), # <= add that comma
if you want the output like this kroy wen then try this:
sys.stdout.write(name[x])
remember to import sys
I have the following python code:
def plot_only_rel():
filenames = find_csv_filenames(path)
for name in filenames:
sep_names = name.split('_')
Name = 'Name='+sep_names[0]
Test = 'Test='+sep_names[2]
Date = 'Date='+str(sep_names[5])+' '+str(sep_names[4])+' '+str(sep_names[3])
plt.figure()
plt.plot(atb_mat_2)
plt.title((Name, Test, Date))
However when I print the title on my figure it comes up in the format
(u'Name=X', u'Test=Ground', 'Date = 8 3 2012')
I have the questions:
Why do I get the 'u'? Howdo I get rid of it along with the brackets and quotation marks?
This also happens when I use suptitle.
Thanks for any help.
plt.title receives a string as it's argument, and you passed in a tuple (Name, Test, Date). Since it expects a string it tried to transform it to string using the tuple's __str__ method which gave you got output you got. You probably want to do something like:
plat.title('{0} {1}, {2}'.format(Name, Test, Date))
How about:
plt.title(', '.join(Name,Test,Date))
Since you are supplying the title as an array, it shows the representation of the array (Tuple actually).
The u tells you that it is an unicode string.
You could also use format to specify the format even better:
plt.title('{0}, {1}, {2}'.format(Name, Test, Date))
In Python > 3.6 you may even use f-string for easier formatting:
plt.title(f'{Name}, {Test}, {Date}')
I'd like to add to #Gustave Coste's answer: You can also use lists directly in f-strings
s="Santa_Claus_24_12_2021".split("_")
print(f'Name={s[0]}, Test={s[1]}, Date={s[2]} {s[3]} {s[4]}')
result: Name=Santa, Test=Claus, Date=24 12 2021. Or for your case:
plt.title(f'Name={sep_names[0]}, Test={sep_names[2]}, Date={sep_names[5]} {sep_names[4]} {sep_names[3]}')
I have some code:
multi = "testtest"
if(type[0] == multi[0]):
print("test")
But then if I run it, it works, but if I type t, the 1st letter, and then some other letters:
tfdsajfdsaf, it won't print test. Is there any other way I could make this work if the other letters are different?
Sounds like you might want to use startswith(), which is a part of the string class.
if string_name.startswith(multi[0]):
print 'test'
You can also use slices:
if string_name.startswith(multi[:3]):
print 'test'