I'm pretty new to python, and I wonder how I can print objects of my class fracture. The str funcion is set properly, I guess
def __str__(self):
if self._denominator == 1:
return str(self._numerator)
else:
return str(self._numerator)+'/'+str(self._denominator)
because of
>>>print ('%s + %s = %s' % (f1,f2,f1+f2))
1/3 + -1/4 = 1/12
Now I'd like to print it properly as a sorted array, and I hoped to get something like
>>>print(', '.join(("Sam", "Peter", "James", "Julian", "Ann")))
Sam, Peter, James, Julian, Ann
But this didn't work for my fracture or even for numbers (like print(' < '.join((1,2,3))))
All I got was:
for i in range(len(fractures)):
if i+1 == len(fractures):
print (fractures[i])
else:
print (fractures[i], end=' < ')
Is this really the best solution? That's quite messing up the code, compared on how easy this works with strings...
If you want to print "1 < 2 < 3" all you need to do is change the type from an int to a string as such:
print(' < '.join(str(n) for n in (1,2,3)))
You have to convert the ints to strings first:
numbers = (1, 2, 3)
print(' < '.join(str(x) for x in numbers))
You can convert your array using map:
print(' < '.join(map(str,(1,2,3))))
You can convert integers to string.
print(' < '.join((str(1),str(2),str(3))))
Related
user_input = (input("Enter: ")).lower()
for item in user_input:
output = chr(ord(item)+1)
print(output, end="")
#I have tried this but while I run the program the after z it is printing {. But I need to print a after z. How can it be done?
Use modulo arithmetic. In place of
chr(ord(item)+1)
you can use:
chr(ord("a") + (ord(item) - ord("a") + 1) % 26)
(For efficiency, you could store the ord("a") in a variable rather than evaluate it every time.)
I am new in python. I have a for loop inside which I have if ...: condition.
I want to print out the (list) of items which went through the for loop.
Ideally, items should be separated by spaces or by commas. This is a simple example, intended to use with arcpy to print out the processed shapefiles.
Dummy example:
for x in range(0,5):
if x < 3:
print "We're on time " + str(x)
What I tried without success inside and outside of if and for loop:
print "Executed " + str(x)
Expected to get back (but not in list format), maybe through something like arcpy.GetMessages() ?
Executed 0 1 2
phrase = "We're on time "
# create a list of character digits (look into list comprehensions and generators)
nums = [str(x) for x in range(0, 5) if x < 3]
# " ".join() creates a string with the elements of a given list of strings with space in between
# the + concatenates the two strings
print(phrase + " ".join(nums))
Note. A reason for the downvotes could help us new users understand how things should be.
Record your x's in a list and print out this list in the end:
x_list = []
for x in range(0,5):
if x < 3:
x_list.append(x)
print "We're on time " + str(x)
print "Executed " + str(x_list)
If you use Python3 you could just do something like this..
print("Executed ", end='')
for x in range(0,5):
if x < 3:
print(str(x), end=' ')
print()
So I've defined a recursive function numToBaseB that converts a given number in base ten into any other base between 2 and 10. The desired output is a string, but for some reason I keep getting an int.
def numToBaseB(num, b):
if num == 0:
return ''
elif b > 10 or b < 2:
return "The base has to be between 2 and 10"
else:
return numToBaseB(num // b, b ) + str(num % b)
So for me:
numToBaseB(4, 2) would return
100
instead of the desired output:
'100'
Your program is working as designed:
>>> numToBaseB(1024,2)
'10000000000'
>>> numToBaseB(4,2)
'100'
Of course, if you do print(numToBaseB(4,2)), the quotes will not be displayed.
If you want to have quotes though, you can always do this:
print (" ' "+numToBase(4,2)+" ' ")
But in the program, if you use str() anyways, it will be treated as string ofcourse.
:)
Edit: typing on phone, so sorry for this madness :(
I have to add str(iterMul(a,b)) to obtain what I want. Is it the proper way to do it?
def iterMul(a,b):
result = 0
while b > 0:
result += a
b -=1
return result
a=int(raw_input('Enter an integer: '))
print('')
b=int(raw_input('Enter an integer: '))
print('')
print (str(a) + ' times '+str(b)+' is equal to '+ str(iterMul(a,b)))
Thanks in advance!
Use string formatting instead:
print '{0} times {1} is equal to {2}'.format(a, b, iterMul(a,b))
String formatting automatically transforms integers to string when interpolating the values, and is more readable than print value, ' some text ', othervalue, ' more text and ', thirdvalue.
I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
This always returns false because y becomes something like <reversed object at 0x00E16EF0> instead of the reversed string.
What am I being ignorant about? How would you go about coding this problem?
Try y = x[::-1]. This uses splicing to get the reverse of the string.
reversed(x) returns an iterator for looping over the characters in the string in reverse order, not a string you can directly compare to x.
reversed returns an iterator, which you can make into a string using the join method:
y = ''.join(reversed(x))
For future reference, a lambda from the answers above for quick palindrome check:
isPali = lambda num: str(num) == str(num)[::-1]
example use:
isPali(9009) #returns True
Try this code.
def pal(name):
sto_1 = []
for i in name:
sto_1.append(i)
sto_2 = []
for i in sto_1[::-1]:
sto_2.append(i)
for i in range(len(name)):
if sto_1[i] == sto_2[i]:
return "".join(sto_1), "".join(sto_2)
else:
return "no luck"
name = raw_input("Enter the word :")
print pal(name)
list(reverse( mystring )) == list( mystring )
or in the case of numbers
list(reverse( str(mystring) )) == list( str(mystring) )
Try this code:
def palindrome(string):
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("hannah")
Try this code to find whether original & reverse are same or not:-
if a == a[::-1]:
#this will reverse the given string, eventually will give you idea if the given string is palindrome or not.