Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I was working with f-strings, and I am fairly new to python. My question is does the f-string formatting cast a variable(an integer) into a string?
number = 10
print(f"{number} is not a string")
Is number cast into a string?
f"..." expressions format values to strings, integrate the result into a larger string and return that result. That's not quite the same as 'casting'*.
number is an expression here, one that happens to produce an integer object. The integer is then formatted to a string, by calling the __format__ method on that object, with the first argument, a string containing a format specifier, left empty:
>>> number = 10
>>> number.__format__('')
'10'
We'll get to the format specifier later.
The original integer object, 10, didn't change here, it remains an integer, and .__format__() just returned a new object, a string:
>>> f"{number} is not a string"
'10 is not a string'
>>> number
10
>>> type(number)
int
There are more options available to influence the output by adding a format specifier to the {...} placeholder, after a :. You can see what exact options you have by reading the Format Specification Mini Language documentation; this documents what the Python standard types might expect as format specifiers.
For example, you could specify that the number should be left-aligned in a string that's at least 5 characters wide, with the specifier <5:
>>> f"Align the number between brackets: [{number:<5}]"
'Align the number between brackets: [10 ]'
The {number:<5} part tells Python to take the output of number.__format__("<5") and use that as the string value to combine with the rest of the string, in between the [ and ] parts.
This still doesn't change what the number variable references, however.
*: In technical terms, casting means changing the type of a variable. This is not something you do in Python because Python variables don't have a type. Python variables are references to objects, and in Python it is those objects that have a type. You can change what a variable references, e.g. number = str(number) would replace the integer with a string object, but that's not casting either.
You can test it yourself quite easily
number = 10
print(f"{number} is not a string")
print(type(number))
# output is integer
If u can't understand f string or other soln dosent make any sense then try this.
This will help you integrate a variable(integer/char) in a string.
a = "blah blah blah {} blah blah ".format(integer_value)
print(a)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
While learning python, I could not find the difference between the use of str() and " ".
First code
Second code
With str() function you are changing the number type to String but with "" you just pass the String.
str(3.14) # 3.14 is a number and your are converting it into String.
"3.14" is an String value.
Imagine if you had a variable
pi=3.14
then
str(pi)
would give the result 3.14
whereas
"pi"
would give the result pi. The str() function converts something to its string form. Whereas simple quotes will return the word itself.
str() returns a string representation of an object, while quotation marks indicate the value is a string. To see the difference, consider the following:
x = 3.14
print("x") #outputs the character x
print(str(x)) #string representation of the value of object x
In the first print(), the actual character 'x' is output. This has nothing to with the variable x. However, in the second print(), the value of the object x is converted to a string, so '3.14' is output.
There is no difference between the two. The program will run the same. CodeCademy requires that you use the skills (functions and methods) that it teaches you in that step in order to progress to the next one. The python script doesn't do anything differently, but the CodeCademy code analyzer notices that you didn't accomplish the task the way they wanted you too.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to keep a string I've converted from an integer. I can convert an int variable into a string, but then I can't seem to interact with that. Here's how it goes in the Python shell:
a = 100
a
>>> 100
str(a)
>>> '100'
a
>>> 100
str(a) = b
>>> SyntaxError: can't assign to function call
What I need is to turn this '100' string into a new variable. I've tried searching; the answer is probably out there, but I'm clearly not using the right search terms. All the answers I've found have only been concerned with how to convert from one type to another.
The problem you are experiencing is not the problem that you think you are experiencing.
When you define a variable in Python, the variable goes on the left of the equals sign. It should look like this:
b = str(a)
This will define b without giving you an error message. Going back to your question, if you want to change a to a string and keep it that way, str(a) will not suffice. Instead:
a = str(a)
Will change your variable to a string. str(a) is simply a function that returns the variable a in the form of a string. If you do not redefine a here, str(a) will not return to anywhere and your string will be lost.
You have your assignment syntax back to front. The target name goes on the left:
b = str(a)
Now b is a reference to the return value of str().
You can also re-assign back to a, replacing the old integer value with the string representation:
a = str(a)
Your attempt instead tried to use str(a) as an assignment target; Python can't let you do that because the result of str(a) is unknown when the code is compiled; you cannot bind any object to another, you need to have a reference instead (so a name, or an attribute, or a list index, or a dictionary key, etc.).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary units depending on the study it comes from. Here is an example of what I mean:
[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2]
These are of course of type:
<type 'numpy.float64'>.
If I print out the last number, for instance:
print list[-1]
>>> 7.2
However, if accessed in this way, I get:
7.2000000000000002
I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:
[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]
Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?
You have three problems:
1) How do I determine the number of decimal places in the input?
If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.
If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:
for line in input_file:
data = [float(x) for x in line.split(',')]
You need to record the number of places to the right of the decimal before converting to float, for example:
for line in input_file:
places = [len(x.partition('.')[2]) for x in line.split(',')]
data = [float(x) for x in line.split(',')]
2) How do I store that information?
That's up to you. Sorry, I can't help you with that one without seeing your whole program.
3) How do I format the output to round to that number of decimal places?
Use the % operator or {}-style formatting, like so:
print '%.*f' % (places[i], data[i])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm working in a program that needs to compare strings that have about 900 digits.
But whenever I enter them as
a = '01111111111111100000000000111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111010101000000000000000000000000000000011111111111111111111111111111111111111100000000000000000000000000000000000000000000111111111111111111111111111100001010101000010100'
Python only takes the first line as the string, and it says error.
In which way can I enter it so that Python takes the complete string?
Thanks
You mean you need to enter a multi-line string with newlines?
Use triple quoting:
a = '''This is the first line
and a second one too
hello world!
'''
Newlines are preserved, as is all whitespace.
If you didn't want to include newlines, use parenthesis around multiple strings:
a = (
'This is one string, '
'entirely without newlines, but it is one long '
'string nonetheless')
The Python compiler makes such consecutive strings (without anything but whitespace in between) into one long string object.
However, a 900 digit string is perhaps best stored in a separate file, not in your source code:
with open('digitsfile.txt', 'r') as infh:
a = infh.read().strip() # read all data, remove newline at the end
The Python compiler concatenates adjacent string literals. You just need to tell the compiler that the literals are adjacent.
a = (
'123'
'456'
'789'
)
print a
you can skip new line by \:
>>> num = '12345' \
... '67890'
>>> num
'1234567890'
Are you sure there is no carriage return in the string somewhere, that would cause an error.
Try enclosing the string in triple quotes
s = """really long strrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrring"""
and then echo it back
print s
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using python to do some text comparison. The text format is like 44=100. Let's say, I have 2 text, 44=100 and 44=3001. I call the string on the left of = is tag, right is value. Now I need to compare the tag and value for them. The tag must be the same, 44 equals 44, but the values don't have to, as long as its format is the same. ie. 100 and 3001 are in the same format(normal digits). But 1.0E+7 in 44=1.0E+7 is different. tThe point is on value comparison. ie. I write a script comp.py, when I run comp.py 2000 30010, I will get output true; while I run comp.py 100000 1.0E+8, output is false. How can I do it? I am thinking about converting the value into an regular expression and comparing it with other.
pseudo code:
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Is it a feasible way? any advice?
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Your approach is wrong. It is not only difficult but also illogical to "deduce" a regexp from a given string. What you would do is:
Define your types. With each type you would have a corresponding regexp.
Compare your input text against all your defined types and check which type it is of.
Compare the two types.
Actually, your idea of rex1 = '100000'.getRegrex() could be done
rex1 = re.compile('10000')
But as Thustmaster pointed out, you may want to define the regular expression with more abstraction of the pattern of your data.