I am trying to make a program that adds a number to a string and prints it. Here is my code:
n1 = 5
n2 = 6
statement = "number 1: ",n1,") (number 2: ",n2,")"
print(statement)
I want it to print (number1: 5 ) * (number2: 6 ).
EDIT:
The problem I had was my items were separated by commas, not plus signs. This caused an error becuase you need to seperate things with plus signs.
3 ways to get around this would be:
A:% formatting
number = 1
statement = "Your number is %s." % (number)
B:{} formatting
number = 2
statement = "Your number is {}.".format(number)
C:Converting to a string
number = 3
statement = "Your number is "+str(number) + "."
You are trying to join strings using the comma operator. This creates a tuple, not a string. Strings are concatenated using the + operator, like so:
statement = "(x +" + str(n1) + ") * (x +" + str(n2) + ")"
But it would be even easier to use the string formatting operators:
statement = "(x + {}) * (x + {})".format(n1,n2)
or
statement = "(x + %s) * (x + %s)" % (n1, n2)
Your syntax in line 4, where you build the statement, is one that constructs a list from comma-separated elements. You need to convert the integers to strings somehow, and work in the spaces you want. Here's the closest equivalent, I think:
statement = "(x + " + str(n1) + " ) * (x + " + str(n2) + " )"
This prints the output you requested.
When you construct your "statement" variable, you are building a tuple, not a string (those commas are the culprit).
Build that variable as a string, and you'll be able to add it to the other string.
statement = "(x + {n1}) * x +{n2})".format(n1=n1, n2=n2)
Related
I am trying to get this output:
+-+-+-+-+-+-+
|P|Y|T|H|O|N|
+-+-+-+-+-+-+
Is it possible to get that output without adding new lines in the code?
def art(name):
for i in range(len(name[0]), len(name) + 1):
head = "+" + i * "-+"
middle = "|" + i * "{}|".format(name[0].upper())
bottom = "+" + i * "-+"
print(head + "\n" + middle + "\n" + bottom)
art("Python")
Actual output:
+-+-+-+-+-+-+
|P|P|P|P|P|P|
+-+-+-+-+-+-+
I can't figure out how to manipulate it in order to get it to work. I've tried to use use index() and i as a variable but I get errors such as: "IndexError: string index out of range"
You have hardcoded the index 0 when you're looking up the character to print:
def art(name):
for i in range(len(name[0]), len(name) + 1):
head = "+" + i * "-+"
middle = "|" + i * "{}|".format(name[0].upper())
^-- here
bottom = "+" + i * "-+"
print(head + "\n" + middle + "\n" + bottom)
art("Python")
Instead, you can use i to reference the actual character in name:
middle = "|" + i * "{}|".format(name[i].upper())
You also have an error in your range. There is no need to use len(name[0]) - this will always be 1, and will cause your loop to run one iteration longer than the length of name (since indexes start on 0). This is the cause of your IndexError.
Instead, use 0 as the start - which is the same as not giving a start argument at all:
for i in range(len(name)):
But you don't actually need the index; there is no need to iterate over the name to do what you want. You can instead join each letter in name with | as the separator. The header/footer can be created by repeating +- the same amount of time as the length of name. So your loop can be replaced with:
print('+-' * len(name) + '+')
print('|' + '|'.join(name.upper()) + '|')
print('+-' * len(name) + '+')
.. or assigned to head, middle, bottom if you want that instead.
head and bottom don't need to be in the for loop, because they calculate the full string all at once. For that matter, because they're the same string, there's no reason for them to be two separate variables at all.
Your loop doesn't need to loop over indexes -- it can loop over characters, so you can directly add those characers yourself; and using an f-string is somewhat unnecessarily overcomplicated.
Anyhow -- if you're going to be using a loop, you should be additively constructing your string; just overwriting the whole thing on every iteration makes there no point to using a loop at all.
def art(name):
head = "+" + len(name) * "-+"
middle = ''
for character in name:
middle += '|{}'.format(character.upper())
print(head + "\n" + middle + "|\n" + head)
art("Python")
I am trying to create a program that is sort of an "expander". If you were to give it a number like 1234, it should return "1000 + 200 + 30 + 4". However, I keep getting an int object is not subscript able error even thought I made proper conversions.
I have tried having new_str = num[int(i)] ... but that still doesn't work.
def expanded_form(num):
count = len(str(num))-1
new_str = ""
for i in range(0,len(str(num))):
new_str += num[i] * 10**count + " + "
count -= 1
return new_str
print(expanded_form(1234))
The problem is inside the for loop, you're writing num[i], that's what's giving you the error since num is an int and you can't really access an index of an int.
You're trying to get the number on that index and multiply it by 10 ** count. To do that should try this
new_str += str(int(str(num)[i]) * 10 ** count) + ' + '
You first have to turn num into a string to get the number on that position, but it returns it as a string, so you have to parse it back to int in order to multiply it with 10 ** count, and then you have to turn it into a string again in order to concatenate it with ' + '.
If you want to avoid parsing it so many times try doing this inside the for loop
new_str = str(num)[i] + '0' * count + ' + '
Instead of mutiplying it by a power of 10 you can use the fact that count is the number of zeros that should follow str(num)[i]
Your error is telling you that you cannot subscript an integer. Here: num[i]. num is an integer. You should cast it again to a string.
This said, to do what you want you need to recast the digit num[i] to an int in order to do the math.
def expanded_form(num):
count = len(str(num))-1
new_str = []
for i in range(0,len(str(num))):
new_str.append(int(str(num)[i]) * 10**count)
count -= 1
return ' + '.join(map(str, new_str))
print(expanded_form(1234))
Note that I made new_str a list and use join to build the string with the sum, to get rid of the extra '+' at the end. I also needed map to convert back all the integers to string otherwise join does not work.
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 1 year ago.
I was writing a script in Python to generate brute force wordlists. I already can concatenate only strings, but I cant concatenate some random numbers in the final of each word in list, because it says that I cannot concatenate str and int objects...
The code:
wList = []
words = raw_input("[+]Insert the words that you wish: ")
outputFile = raw_input("[+]Insert the path to save the file: ")
wordList = words.split(",")
for x in wordList:
for y in wordList:
wList.append(x + y)
wList.append(y + x)
wList.append(x + "-" + y)
wList.append(y + "-" + x)
wList.append(x + "_" + y)
wList.append(y + "_" + x)
wList.append(x + "#" + y)
wList.append(y + "#" + x)
for num in wordList:
for num2 in wordList:
for salt in range(1,10):
wList.append(num + num2 + int(salt))
wList.append(num2 + num + int(salt))
In python the + operator after a sequence calls concat with the sequence before the operator and whatever is after the operator. In python string is a sequence. The concat function only works on two sequences of the same type, i.e. two strings or two arrays. In your code you use this operator for string and int.
You need to change all of the places you concatenate strings with ints. Here are two possible ways to do this.
You could make all the ints into strings. For example:
wList.append(str(x) + "-" + str(y))
Or you could use %-formatting. For example:
wList.append("%d-%d"%(x, y))
You can only concatenate a string with another string in Python.
Change the last two lines to below:
wList.append(num + num2 + str(salt))
wList.append(num2 + num + str(salt))
I'm trying to make an algorithm in Python 2.7.10 that takes user input, splits it and puts words into a list, then takes all words from that list and prints them in a specific manner.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
print "You think that the painting is:"
print "%s" + ", %s" * len(input) + "." % ( > ? < )
The %s formatters work as placeholders. The problem is that the number of placeholders that will be printed as a part of the string isn't fix, it's equal to len(input). Therefore I don't know how to assign values to these formatters. (That's the " > ? < " part inside of the brackets.)
Note: as this is for test purposes only, let's assume the user will only be inputting strings, not integers, etc. so that there is no need for the %r formatter.
The desired output should look somewhat like this:
> nice pretty funny
You think that the painting is:
nice, pretty, funny.
I know this can be achieved using the str.join(str) method but is there a way of doing it as I explained above? Thanks.
Use print ("%s" + ", %s" * (len(input) - 1) + ".") % tuple(input)
However, IMO ', '.join(input) + '.' is better :)
You can do what you want by doing this:
print ",".join(["%s"] * len(input)) % tuple(input)
Basically, construct your string of "%s, "... and pass the input as a list to the string formatters. You can do it exactly like you've written it too, just pass in your list.
print "%s" + ", %s" * len(input)) + "." % tuple(input)
You should use a tuple after "%". Note that you have already considered the first word in the print, so len(input) -1 words are left to be written.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
output = "%s" + ", %s" * (len(input) - 1) + "."
print "You think that the painting is:"
print output % tuple(input)
I've been working on HTTLCS and am having some difficulty finishing up the problem.
Solving a problem was not much of an issue, but I have trouble returning my result as a string rather than the tuple data type.
Here is my code:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains", wordnum, "words, of which" , eWordnum , "(" , percent , "%)" , "contains an 'e'."
print(wordCount(p))
Python outputs ('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.") which is a tuple, not a string.
I know I can just put print at the end of the function and call the function without print() statement, but how do I solve this with a return statement?
It's because you're using commas in your return statement, which Python is interpreting as a tuple. Try using format() instead:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)
>>> wordCount("doodle bugs")
"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
return "Your text contains " + str(wordnum) +
" words, of which " + str(eWordnum) +
" (" + str(percent) + "%)" + " contains an 'e'."
or
return "Your text contains %s words, of which %s (%s%%) contains an 'e'."
% (wordnum, eWordnum, percent)
In the first case, you do a string concatenation and you have to convert wordnum, eWordnum and other variables that are numeric ones, into str (by doing str(variableName)) to allow the concatenation (and for haven't runtime error)
In the second case, you do a string replacement that means that you give some kind of "placeholder" %s (that means string) and you replace them with tuple argument that follows the % symbol
If you return something separate by , you'll return a tuple (as you can see)
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
A for loop might work, though you would have to format the strings to add spaces to them.
for item in tuplename: print item,
Make sure to keep the comma after item, because that prints it on the same line.
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
dummy = "Your text contains {0} words, of which {1} {2} contains an 'e'.".format(wordnum,eWordnum, percent)
return dummy
print(wordCount(p))
try this :
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
using %(variable_name)s as string formatting is often easier to maintain.
how about this
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."
replace the commas with "+", this should work.