I have tried this but its working
For example:
x= 523.897
y= x[0:"."]
print y
I want to print 523 only. How do I make Python grab a string till a certain letter or number?
I have tried this but its working
For example:
x= 523.897
y= x[0:"."]
print y
I want to print 523 only. How do I make Python grab a string till a certain letter or number?
The line y = x[0:"."]
is not valid Python. I get what you're trying to do, though. Try this:
x = 523.897
x = str(x)
y = x[:x.find('.')]
Although, from your last line, it looks like you just want the integer value of 523.897
. You can use int(523.897)
(or int(x)
in your case) to do this.
Going under the hood, you'll see that x.find('.')
returns 3, or the index at which '.'
first appears. So you're really indexing the string '523.897'
from 0 to 2, inclusive. A relevant link: Explain Python's slice notation.
Edit:
@Keerthana's right: if '.'
isn't in the string, the above approach will return the "incorrect" output according to the output you've outlined above. This is because -1
is returned when the character is not found in the string. There are many ways to get around this, like using str.split
, but my case works in the case of every string containing the character you're looking for.
You can use string.split(s[, sep[, maxsplit]])
as
If maxsplit is given, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
y = x.split(delim,1)[0]
That is,
>>> x = 523.897
>>> x = str(x)
>>> delim='.'
>>> y = x.split(delim,1)[0]
>>> print y
'523'
>>> x='Hakona Matata'
>>> delim = 'n'
>>> y = x.split(delim,1)[0]
>>> print y
'Hako'
Hope this helps!
You can also use str.split() to split the string at the dot
x = 523.897
d = r"."
x = str(x).split(".")[0]
A regex way will be:
x = 523.897
d = r"."
x=re.search(r"(?P<x>.+)"+d+r"?", str(x)).group("x")