Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm beginning to learn the basics of python. I had just learned that str() turns non-strings into strings - example: str(2) would change 2 to "2". That raised a question - what is a string and what difference does it have from a non-string? I've googled this but I could not find this question is directly answered and the general explanations don't quite make it clear for me.
"That raised a question - what is a string and what difference does it have from a non-string?"
It sounds like python is your first language. That being said, for conceptual sake, a string is text, and a 'non-string' is a number. You will see why this is not quite true as you program more, but for understanding the difference between a string and a 'non-string' this will suffice. You can do math with 'non-strings'. "2" is a string, but 2 is a 'non-string'. Adding strings is NOT the same as arithmetic addition. "2" + "2" results in another string "22" (this operation is called concatenation ), but 2 + 2 results in a 'non-string' A.K.A. the NUMBER (not string) 4, because the addition is arithmetic addition.
A string is any sequence of characters — not just numbers, but letters and punctuation and all of Unicode.
Something that isn't a string is... not that. :) (There are lots of things that aren't strings! String isn't special.) For example, 2 is an int. You can do math on an int, because it's a number. But you can't do math on a str like "2"; it's only the way we write the number in Western mathematics, not the number itself. You couldn't ask "dog" to wag its tail, either, because it's not a real dog; it's just the written word "dog".
As a more practical example:
2 + 2 gives you 4, the result of combining two numbers.
"2" + "2" gives you "22", the result of combining two written "words".
just to put another spin on this...
objects in python come with a variety of attributes and methods. attributes tend to represent data associated with the object. methods tend to represent behaviors that can be performed by the object. if we create a string and give it the name a and look at the list of attributes/methods, we see that the list encompasses many of the things you would want to know about a string or do with a string.
In [91]: a = '1' # assign a string the name 'a'
In [92]: a.
a.capitalize a.format a.isupper a.rindex a.strip
a.center a.index a.join a.rjust a.swapcase
a.count a.isalnum a.ljust a.rpartition a.title
a.decode a.isalpha a.lower a.rsplit a.translate
a.encode a.isdigit a.lstrip a.rstrip a.upper
a.endswith a.islower a.partition a.split a.zfill
a.expandtabs a.isspace a.replace a.splitlines
a.find a.istitle a.rfind a.startswith
on the other hand, if we create a number and give it the name b and look at the list of attributes/methods, we see that they are very different and focuses on things we would want to know about a number or do with a number.
In [92]: b = 1 # assign a number the name 'b'
In [93]: b.
b.bit_length b.denominator b.numerator
b.conjugate b.imag b.real
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a dataset of phone numbers that I want to check against each other. Basically the regex should throw a match if two phone numbers are at most 1 digit apart. For example, we have the following phone numbers:
+31612345678
+31612245678
These numbers are the same apart from position number 7 (first number has a 3 while the second number has a 2). As these phone number differ by 1 digit, the regex should throw a match. It stands to reason that the regex should also throw a match if the phone numbers are exactly the same. In the following case (see below), the regex should however not throw at match as the phone numbers differ by more than 1 digit:
+31612345678
+31611145678
Does anyone have a good regex in mind? I am writing the regex using the re module in python.
Depending on your use case - if you want to also catch "oh, you missed a digit" or "eh, that digit shouldn't have been there", use the edit distance between the two numbers instead.
You can use the levenshtein edit distance to get a number for how many "edits" would be required between two numbers, for example by using the editdistance library for python.
>>> import editdistance
>>> editdistance.eval('banana', 'bahama')
2L
This may not be the best code, but it would do the job.
from collections import Counter
a = '+31612345678'
b = '+31612245678'
def match(p1, p2):
ct = Counter([a == b for a, b in zip(p1, p2)])
if not ct[False] > 1:
<throw match>
You wouldn't use a regular expression for this. If your phone numbers have the same length something simple as
def is_match(phone_nr_1, phone_nr_2):
diff = filter(lambda x: x[0] != x[1],
zip(phone_nr_1, phone_nr_2))
return len(diff) <= 1
print is_match("+31612345678", "+31612245678")
#=> True
print is_match("+31612345678", "+31611145678")
#=> False
would do the job.
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 7 years ago.
Improve this question
I have some floating point values, these all values are dynamically generated:
float_a = 12.200
float_b = 14.0
float_c = 14.01880
I want to remove the decimal point from them.
Expected Result
"12200"
"140"
"1401880"
I must be careful as these are not fixed-point values and I don't have any control on how many decimal places my input will go up to. More examples from the comments:
1.10
1.110
2.0
2.1340
Expected result:
"110"
"1110"
"20"
"21340"
This question seems to be a permutation of another question that has already been answered:
The concept of leading zeros is a display concept, not a numerical
one. You can put an infinite number of leading zeros on a number
without changing its value. Since it's not a numeric concept, it's not
stored with the number.
You have to decide how many zeros you want when you convert the number
to a string. You could keep that number separately if you want.
SOURCE: Python Force python to keep leading zeros of int variables
It looks like the only way to do what you are asking is if your initial "Float" is in string form, otherwise the trailing 0's will be dropped. If you manage to get the "Float" as a string (before it ever becoming a Float), then you can use the int('12.200'.replace('.', '')) method mentioned above
If you're starting off with a string, which I think you are. I would use something like:
>>> int('12.200'.replace('.',''))
12200
It just removes the . and parses the resulting string as an int. Otherwise just cast whatever you have to str first.
It is just a formatting issue. Either of these work to get trailing zeroes:
>>> '{:.3f}'.format(1.2)
'1.200'
>>> '%0.3f' % (1.2,)
'1.200'
Then:
>>> '{:.3f}'.format(12.2).replace('.','')
'12200'
To get what you want from your examples:
vals=(1.10, 1.110, 2.0, 2.134)
def wid(f):
w=1
while True:
s='{:.{w}f}'.format(f, w=w)
if s[-1]=='0' or w>5:
break
w+=1
return w
for e in vals:
s='{:.{w}f}'.format(e, w=wid(e)).replace('.','')
print '{:10} => {}'.format(e, s)
Prints:
1.1 => 110
1.11 => 1110
2.0 => 20
2.134 => 21340
If you want to remove the decimal, why not multiply by 1000?
float_a = 12.200
print str(int(float_a*1000))
When you have
float_a = 1.110
float_b = 1.1100
float_c = 1.11000
Python is discarding the trailing zeros, and the above 3 are the exact same. These trailing zeros are non-significant digits, and so if you want to actually preserve them, your original data type will need to be a String.
If you make that change, then it is simple to do
float_a = "1.110"
print float_a.replace('.', '') # "1110"
If you're asking how to turn float_a = 12.200 into the string "12200", simply multiply it by 1000 before converting it into a string, for example:
print(str(float_a * 1000))
However, if the number contains more than 4 decimal places, you'll still have decimals.
However, since you're talking about it "always removing the 0's", I suspect you may have missed a . in your expected output. In this case, to display a float with a fixed number of decimals, just use Python's built-in string formatting:
float_a = 12.200
expected_result = '%.2f' % float_a
print expected_result
> 12.20
If this doesn't make sense, please clarify your question a bit and I'll edit! :)
Edit
Upon your further clarification of the question, it seems that you want to define a float with trailing zeros and have them preserved and the float converted to a string with the leading zeros preserved. I'm afraid this is impossible if your input type is float, since float won't preserve those trailing zeros to begin with:
In [1]: float_a = 3.1400
In [2]: float_a
Out[2]: 3.14
This is a "limitation" of the data type and there's nothing you can do about it. You want a fixed-point type or something to handle "decimal numbers", not a float.
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
I need a way to multiply all the numbers in a string by another number while keeping the structure and format of the string. Can it be done?
For example:
my_var = """Cat, 5, kg
Dog, 10, kg
Human, 50, kg"""
Given this string, I want to be able to multiply 5, 10 and 50 by another number saved in some other variable.
multiplier = 2.0/10 # or 0.2
So I want to use multiplier and my_var to create a new string:
"""Cat, 1, kg
Dog, 2, kg
Human, 10, kg"""
that I would then output to the user.
Any help would be appreciated!!
Regular expressions with a custom substitution function seem to suit the task well.
We can find all numbers in a string, convert them to integers and perform some arithmetic on them. After that they need to be converted back to strings to replace the former text.
import re
text = '''
Cat, 5 kg
Dog, 10 kg
Human, 50 kg
'''.strip()
def divide_numbers(s, n):
def sub(m):
return str(int(m.group(0))//n)
return re.sub('[0-9]+', sub, s)
print(divide_numbers(text, 5))
Cat, 1 kg
Dog, 2 kg
Human, 10 kg
Do notice that fractional parts are discarded everywhere here. You may want to use float instead of int and / instead of // (which is integer division).
Another interesting advantage of regular expressions here is you can make your pattern more advanced to match only some numbers. Here we match only the numbers that are followed by " kg", and I changed to float as mentioned
def divide_numbers(s, n):
def sub(m):
return str(float(m.group(1))/n)
return re.sub('([0-9]+) kg', sub, s)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to round some negative floating numbers, the format i want is like the below print/format way, not the round. The problem is that the print approach is not "clean", since it outputs a string with spaces, I got this code from another similar question here in Stackoverflow. The question is how to format/round the numbers like the print below. Thank you
theta = 0.33161255787892263
math = 0 + (1-0) * (1-math.cos(theta))**5
round(math,8) # Result: 4.8e-07 #
print("{:18.8f}".format(math)) # Result: ' 0.00000048' #
You say "I want the result of the print but in a float number not string" and "The result returns to a negative power floating point number, i want to keep the decimal format as the string". But you can't do that because you have no control over the internal representation of a float: they are all stored in a binary form of scientific notation. See the Wikipedia article on floating-point numbers for details.
So it doesn't matter whether you do
v = 0.00000048
or
v = 4.8e-07
both of those statements have an identical effect.
Note that many fractional numbers that terminate when written in decimal may repeat when written in binary. The only fractions that terminate when written in binary are of the form n / (2 ** b), where n and b are integers. Thus even an innocuous-looking number like 0.2 doesn't terminate when converted to binary. (See the Wiki link for a fuller explanation). Because of this issue it's generally not a good idea to round floating-point numbers until you've finished all calculations with them.
If you convert a string to float and back again it has to be converted from decimal to binary and back again. So such an operation shouldn't be used in an attempt to "clean up" a number because of the possible rounding errors at each conversion step.
Of course, sometimes you do need to apply rounding to a float that you are going to continue calculating with, but if so, you should proceed with caution and make sure you really do understand what you're doing to your data.
...
There are a few other strange things with the code you posted.
math = 0 + (1-0) * (1-math.cos(theta))**5
Firstly, you should not use the name of a module that you've imported as a variable name. After the above statement is executed math now refers to the result of the calculation, not the math module, so if you tried to do x = math.cos(0.5) you'd get an error. Similarly, don't use int, str, list, etc as variable names.
Secondly, the 0 + (1-0) * is virtually useless. So the above statement could be re-written as
result = (1 - math.cos(theta)) ** 5
And the whole code snippet would become
#! /usr/bin/env python
import math
theta = 0.33161255787892263
result = (1 - math.cos(theta)) ** 5
print round(result, 8)
print("{0:.8f}".format(result))
output
4.8e-07
0.00000048
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.