PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] How to print an incremented int identifier in a string in Python

 September 15, 2022     printing, python, string-concatenation     No comments   

Issue

In Java, If I want to print an incremented int variable, I can do it as:

int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));

Output:

21
You are 21 years old going on 22

Is it possible to do the same in Python?

I tried the following, and none of them work.

age = input("How old are you?")
print("You are " + age + " years old going on " + str(age+1))
print("You are " + age + " years old going on {}".format(age+1))
print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))

I have already tried the solutions provided in these links:

Print Combining Strings and Numbers

Concatenating string and integer in python

Converting integer to string in Python?

TypeError: Can't convert 'int' object to str implicitly


Solution

You need to convert the input to an int :

>>> age = int(input("How old are you?"))

And then the following work :

print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))


Answered By - 3kt
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing