String reversal in Python - python

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?
I am not able to convert the integer into a list so not able to apply the reverse function.

You can use the slicing operator to reverse a string:
s = "hello, world"
s = s[::-1]
print s # prints "dlrow ,olleh"
To convert an integer to a string, reverse it, and convert it back to an integer, you can do:
x = 314159
x = int(str(x)[::-1])
print x # prints 951413

Code:
>>> n = 1234
>>> print str(n)[::-1]
4321

>>> int(''.join(reversed(str(12345))))
54321

Related

Is there a way to increase numeric value in a string variable? [Python]

I'm trying some web-scraping which requires to loop through some elements having attribute in a string format. But the string is a numeric value which increases throughout the element.
data-id="1"
Is there a way to increase the value of data-id to "2" to "3" so on while it remains in string format?
First, convert the string to an integer, you can do that with the int builtin:
int(data_id)
Then add 1 to that integer:
int(data_id) + 1
Finally, convert the new integer back to a string, you can do that with the str builtin:
str(int(data_id) + 1)
E.g.
>>> data_id = "1"
>>> data_id = str(int(data_id) + 1)
>>> data_id
'2'
I will just explain the response In the comment of #rdas and #Jax Teller code:
First, you convert your string to integer value, for this we use int(my_string), let assume, you store the result in a variable called int_val like int_val = int(my_string),
Then you increase you integer value int_val = int_val + 1,
At the end you convert back the result to string using str(...) : my_str=str(int_val).
my_string = "1"
int_val = int(my_string)
int_val = int_val + 1
my_string = str(int_val)
These steps are compacted in one single line like my_str = str(int(my_str)+1).
Good luck.
something like the below
def increment_str(string):
return str(int(string) + 1)
print(increment_str("12"))
output
13
I would recommend to use an integer variable in the first place and convert it to a string as needed:
data_id = 1
fetch_element_(data_id=str(data_id))
data_id += 1
fetch_element_(data_id=str(data_id))
Now, you can simplify that code using a for-loop and the built-in range function:
for data_id in range(1,4): # This will loop through the numbers [1, 2, 3]
fetch_element_(data_id=str(data_id))
When your first id is given as a string in the beginning, you can use the int constructor to convert it to an int, as suggested in the other answers:
data_id = int("1") # or int(some_string_variable)

How to get string and int as input in one line in Python3?

I have seen the below link for my answer but still didn't get an expected answer.
If I provide Name and Number in one line, Python should take the first value as a string and second as an integer.
a, b = [int(x) if x.isnumeric() else x for x in input().split()]
It will convert to int any part of input if possible.
s, num = input("Give str and int :\n").split()
num = int(num)
print(s, type(s))
print(num, type(num))
Output :
Give str and int :
hello 23
hello <class 'str'>
23 <class 'int'>
If you're certain to have a string and a number you can use list comprehension to get the values of both.
x = "Hello 345"
str_value = "".join([s for s in x if s.isalpha()]) # list of alpha characters and join into one string
num_value = int("".join([n for n in x if n.isdigit()])) # list of numbers converted into an int
print(str_value)
>> Hello
print(num_value)
>> 345
You can get the string and int by using regular expressions as follows:
import re
input_text = "string489234"
re_match = re.match("([^0-9]*) ?([0-9]*)", input_text)
if re_match:
input_str = re_match.group(1)
input_int = re_match.group(2)
see: https://docs.python.org/3/library/re.html

how to convert string to float in python?

I wrote a function that inputs a string expression and i want to split the expression and use some of the content as float. i tried writing num1 = float(temp[0])
but i got an error message saying i cant convert string to float.
How can i do that in python?
Here is the part of my code:
def calculate_from_string(expression):
temp = expression.split(" ")
num1 = float(int(temp[0]))
num2 = float(int(temp[1]))
oop = temp[2]
return calculate_mathematical_expression(num1, num2, oop)
The type of expression is string.
i tried converting it this way but it didn't work on the tester i was using because i got a message that it is an invalid expression. Does anyone know how i can do it?
It would be good if you provided a snippet of your data to us.
I don't know what you were doing but this should work (and it does for me):
str_expression = '1 57 34'
num = [float(i) for i in str_expression.split()]
you could also use a numpy array:
import numpy as np
nums = np.array(str_expression.split(), dtype=np.float)
If your expression contains some alphanumerics, you can just use regular expressions to extract the numbers.
For example:
str_expression = 'bdjsbd bdka2 23 (34 >> 4) * 2ds'
the right way to extract the numbers would be:
import re
nums = [float(i) for i in re.findall('\d+', str_expression)]
def calculate_from_string(expression):
temp = expression.split(" ")
num1 = float(temp[0])
num2 = float(temp[1])
oop = temp[2]
return calculate_mathematical_expression(num1, num2, oop)
float( int( "123.45" ) ) will raise ValueError since int expect [0-9]+ but you have . in the string, which will raise value error.
2nd point if you will call int(4.5) then it will give you 4, so be careful when using int function.
But you can use float(int(string)) if your input string doesn't contain . e.g. float(int("1234")) which will give you 1234.0

How to set the spaces in a string format in Python 3

How can I set up the string format so that I could use a variable to ensure the length can change as needed? For example, lets say the length was 10 at first, then the input changes then length becomes 15. How would I get the format string to update?
length = 0
for i in self.rows:
for j in i:
if len(j) > length:
length = len(j)
print('% length s')
Obviously the syntax above is wrong but I can't figure out how to get this to work.
Using str.format
>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
some string
You can use %*s and pass in length as another parameter:
>>> length = 20
>>> string = "some string"
>>> print("%*s" % (length, string))
some string
Or use a format string to create the format string:
>>> print(("%%%ds" % length) % string)
some string
The format method allows nice keyword arguments combined with positional arguments:
>>> s = 'my string'
>>> length = 20
>>> '{:>{length}s}'.format(s, length=length)
' my string'
You can declare like this:
print('%20s'%'stuff')
20 would be the number of characters in the print string. The excess in whitespace.

Read numbers from string into float

I need to convert some strings to float. Most of them are only numbers but some of them have letters too. The regular float() function throws an error.
a='56.78'
b='56.78 ab'
float(a) >> 56.78
float(b) >> ValueError: invalid literal for float()
One solution is to check for the presence of other characters than numbers, but I was wondering if there is some built-in or other short function which gives:
magicfloat(a) >> 56.78
magicfloat(b) >> 56.78
You can try stripping letters from your input:
from string import ascii_lowercase
b='56.78 ab'
float(b.strip(ascii_lowercase))
use a regex
import re
def magicfloat(input):
numbers = re.findall(r"[-+]?[0-9]*\.?[0-9]+", input)
# TODO: Decide what to do if you got more then one number in your string
if numbers:
return float(numbers[0])
return None
a=magicfloat('56.78')
b=magicfloat('56.78 ab')
print a
print b
output:
56.78
56.78
Short answer: No.
There is no built-in function that can accomplish this.
Longish answer: Yes:
One thing you can do is go through each character in the string to check if it is a digit or a period and work with it from there:
def magicfloat(var):
temp = list(var)
temp = [char for char in temp if char.isdigit() or char == '.']
var = "".join(temp)
return var
As such:
>>> magicfloat('56.78 ab')
'56.78'
>>> magicfloat('56.78')
'56.78'
>>> magicfloat('56.78ashdusaid')
'56.78'
>>>

Categories