This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 2 years ago.
This is my code:
num = input('Amount of numbers:')
num = int(num)
for x in range(1, num + 1):
if x == 1:
print('1st')
elif x == 2:
print('2nd')
elif x == 3:
print('3rd')
elif x >= 4:
print(x, 'th')
This is the output(sample):
Amount of numbers:8
1st
2nd
3rd
4 th
5 th
6 th
7 th
8 th
As you can see, all numbers after 4 have a whitespace between it and 'th'. How do I fix this?
you can optionally give a separator argument of whatever you want for "how comma should behave" (as another option to the other answers...
print("a","b",sep="+")
a+b
so you could just use ""
print("a","b",sep="")
ab
if you do decide to use a single string as the other answers suggest you should really just use string formatting instead of + concatenation
print("{num}th".format(num=x))
Don't use , comma, that automatically gives a space.
So change the last line from:
print(x, 'th')
To:
print(str(x) +'th')
You can convert the number to a string and then print it as
print(str(x) + 'th')
Or you can change the value of the default separator to an empty string rather than the default space:
print(x, 'th', sep='')
Print function
You can convert the number to a string and then print it.
print(str(x) + 'th')
Or just use sep
num = input('Amount of numbers:')
num = int(num)
for x in range(1, num + 1):
if x == 1:
print('1st')
elif x == 2:
print('2nd')
elif x == 3:
print('3rd')
elif x >= 4:
print(x, 'th', sep="")
Using format strings
Or you can just use this though.
print("{num}th".format(num=x))
Or f strings
print(f"{x}th")
Use fornatted string to plugin a variable in a string.
f"{x}th"
Related
This question already has answers here:
How to convert numbers to words without using num2word library?
(24 answers)
How do I tell Python to convert integers into words
(17 answers)
Closed 15 days ago.
I have a game in python, and I wanted to print numbers. however, 1,000,000 doesn't really look as nice. I was wondering if there was a way I could automatically convert numbers like that into numbers like 1 million.
I tried setting up this code to detect the length of a number and to change it respectivly:
def replacer(s, newstring, index, nofail=False):
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
return s[:index] + newstring + s[index + 1:]
def numr(num):
if len(num) == 1:
pass
if len(num) == 2:
pass
if len(num) == 3:
replacer(num, " hundred", 2)
However, when I ran the code, it ourputted this:
None
Any help?
This question already has answers here:
How to convert an integer to a string in any base?
(35 answers)
Closed 2 years ago.
I'm new to python and I required to write a program that includes converting numbers to strings without using any built in functions beside len() and .index(). What I want to do is convert the number into a list of individual integers and iterate through it, finding the corresponding string for each number and inputting it into a new list, and finally piling it all into one string at the end. This is my program:
def convertToString(integer):
strList = []
numList = []
for x in integer:
numList = numList + [x]
if len(numList) == 0:
raise ValueError()
for char in numList:
string = ""
if char == 1:
string = "1"
elif char == 2:
string = "2"
elif char == 3:
string = "3"
elif char == 4:
string = "4"
elif char == 5:
string = "5"
elif char == 6:
string = "6"
elif char == 7:
string = "7"
elif char == 8:
string = "8"
elif char == 9:
string = "9"
elif char == 0:
string = "0"
else:
string = char
strList = strList+[string]
finalResult = ""
for x in strList:
finalResult = finalResult + [x]
return finalResult
The error tells me that: I cannot iterate through the digits of a float or integer. How can I solve this problem?
A slightly verbose solution, using division and modulo operations:
def convertToString(integer):
rv, nums = '', '0123456789'
while True:
n, r = integer // 10, integer % 10
rv = nums[r] + rv
if n == 0:
break
integer = n
return rv
print( convertToString(10023) )
Prints string:
10023
Divide the number by 10 and use modulus 10 to get each digit and pull the str form of the digit from a list.
numstrs = ["0","1","2","3","4","5","6","7","8","9"]
num = 22
s = ""
while num > 0:
s += numstrs[ num%10 ]
num = (int)(num / 10 )
print(s)
The error is correct: you didn't try to iterate through the digits of the integer; you tried to iterate through the integer itself. The object of a for must be an iterable, as the documentation tells you. An integer is an atomic object. The decimal number you see on output is a human-readable representation of the integer, not the integer object.
You can iterate through a list, tuple, string, or any other sequence. Eventually, you will learn about other iterables. You have to do the arithmetic to duplicate what happens when someone asks to print an integer in its decimal form. Look up how to handle base-10 representation. You can learn some of this by looking up how to convert to any number base.
I am trying to process a list of strings in order to get all my strings with 8 characters. If a string has less than 8 characters I fill as many blank spaces as needed to get an 8 character long string before the last 4 characters. I wrote the following function and tried to apply it to a list of strings, but got a list with None values.
def lengthstring(string):
if len(string) == 5:
new_string = string[0] + " " + string[1:5]
elif len(string) == 6:
new_string = string[0:2] + " " + string[2:6]
elif len(string) == 7:
new_string = string[0:3] + " " + string[3:7]
else:
new_string = string
lp = ['7C246', '7B8451', 'NDKW0745', '5B06833']
labels_with_eight_characters = [lengthstring(string) for string in lp]
Thank you!
Just in case you need a more concise version of the code:
def lengthstring(string):
return (
string if len(string) >= 8
else string[:-4] + ' ' * (8 - len(string)) + string[-4:])
labels_with_eight_characters = list(map(lengthstring, lp))
print(labels_with_eight_characters)
This prints:
['7 C246', '7B 8451', 'NDKW0745', '5B0 6833']
This is because you did not return values in your lengthstring function. After new_string = string, add return new_string and your code should run fine.
a little easier would be to use rjust...
for loc in lp:
print(loc.rjust(8, ' '))
I have a list as [1,2,3,a,b,M] and need to increment every variable by 1 .
I have tried for number I can use as :
a = [1,2,3]
for i in range(len(a)):
a[i] += 1
print a
Also for characters I can use :
ch = 'M'
x = chr(ord(ch) + 1)
print ("The incremented character value is : ")
print (x)
But together I am not able to club it. Is there anyway by which i can club it?
You could try a list comprehension
[e+1 if isinstance(e,int) else chr(ord(e) + 1) for e in [1,2,3,'a','b','M']]
This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
How to print without a newline or space
(26 answers)
Closed 5 days ago.
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.
def sq(num):
words = num.split() # split the text
for word in words: # for each word in the line:
print(word**2) # print the word
num = 9119
sq(num)
We can use list to split every character of a string, also we can use "end" in "print" to indicate the deliminter in the print out.
def sq(num):
words = list(str(num)) # split the text
for word in words: # for each word in the line:
print(int(word)**2, end="") # print the word
num = 9119
sq(num)
Alternatively
return ''.join(str(int(i)**2) for i in str(num))
def sq(num):
z = ''.join(str(int(i)**2) for i in str(num))
return int(z)
number=str(input("Enter the number :"))
def pc(number):
digits = list(number)
for j in digits:
print(int(j)**2,end="")
pc(number)
We can also support input of negative numbers and zeros. Uses arithmetic operators (% and //) for fun.
def sq(num):
num = abs(num) #Handle negative numbers
output = str((num % 10)**2) #Process rightmost digit
while(num > 0):
num //= 10 #Remove rightmost digit
output = str((num % 10)**2) + output #Add squared digit to output
print(output)
You can try this variant:
def square_digits(num):
return int(''.join(str(int(i)**2) for i in str(num)))
def square_digits(num):
num = str(num)
result = ''
for i in num:
result += str(int(i)**2)
return int(result)
var = square_digits(123)
print(var)