Beginner_Steve
Beginner_Steve

Reputation: 13

Python, how to concatenate 2 strings of same value, 0

Post for Python. I did read other posts and sure this isn't a duplicate

I created two variables in my Python and they both have the string 0. I tried with 2 different strings of 1 and 0 and when I concatenate them I get 10. But when I concatenate 0 and 0 I get another 0. Code:

a = 0
b = 0
b = int(str(a)+str(b))
print(b)

Output: 0. I would like the output to be 00

Upvotes: 0

Views: 884

Answers (6)

Almog-at-Nailo
Almog-at-Nailo

Reputation: 1182

You are confusing a lot of terminology here, I suggest you follow a tutorial on types in python (or read the documentation)

As to your problem. You are not storing strings in a and b, you are storing integers:

# These will be integers:
a = 0
b = 0

# These will be strings:
a = '0'
b = '0'

notice the quotes on the strings vs the no quotes on the integers.

Then you do this part:

b = int(str(a)+str(b))

you are casting a and b to a string (both containing '0'), and concatinating them, creating the string '00'. that is what you want to print, but then you cast them back to integers using int(). and when you cast a string with leading zeros to int, the leading zeros are omitted, leaving you back with a '0'.

in conclusion, you can fix your code by removing unnecessary type casts, and using correct typing for your variables:

a = '0'
b = '0'
b = a + b
print(b)

or if you need a and b as integers:

a = 0
b = 0
print(str(a) + str(b))

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24059

in this line b = int(str(a)+str(b)) you convert 00 to int and 00 in int convert to 0. you can change your code like below then you get your desire output:

a = 0
b = 0
print(str(a)+str(b))

also maybe this example helps you:

print(00)
# 0
print("00")
# 00

Upvotes: 1

I3lackI3uck
I3lackI3uck

Reputation: 27

this is because mathematically 00 also means 0. so when converting it to int() type it just takes it as a 0.

so in the print statement don't convert into int() let it be in string.

so print(str(a)+str(b))

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

Having leading zeros in a number will be removed. It won't change the value so Python just removes them.

As you can see:

>>> 0123
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
>>> 

Putting 0 in front of a literal gives an error. But if you just do:

>>> int('0123')
123
>>> 

It would automatically strip the zeros.

To fix it don't change it to a integer:

a = 0
b = 0
x = str(a) + str(b)
print(x)

Output:

00

Upvotes: 2

Jayanti
Jayanti

Reputation: 161

If you want output to be '00', keep b as a string. When you convert it to int, Python simplifies it and simply prints a 0.

New Code:

a = 0
b = 0
b = str(a)+str(b)
print(b)

Upvotes: 0

remove the conversion back to int

a = 0
b = 0
b = str(a)+str(b)
print(b)

Upvotes: 1

Related Questions