Can't concatenate string with integer [duplicate] - python

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))

Related

How to move a white space in a string?

I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.

For each String S, print 's even-indexed characters, followed by a space, followed by 's odd-indexed characters

Im trying to do hackerrank challenge but this code is solving 3/10 of the test case.
The challenge is Given a string, S , of N length that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as space-separated strings on a single line. Note: 0 is considered to be an even index
import sys
cases = int(sys.stdin.readline())
for x in range(cases):
str= sys.stdin.readline()
str= [str[x] for x in range(len(str)) if x%2==0 and str[x]!="\n"] +[" "] + [str[x] for x in range(len(str)) if x%2!=0]
str="".join(str)
print(str)
Need some help.
Thanks
The solution depends on how you index characters.
If the first character is index 0:
s = "abcdefghijklmnopqrstuvwxyz"
r = "".join(s[0::2]) + " " + "".join(s[1::2])
print(r)
acegikmoqsuwy bdfhjlnprtvxz
If the first character is index 1:
r = "".join(s[1::2]) + " " + "".join(s[0::2])
print(r)
bdfhjlnprtvxz acegikmoqsuwy

Int object is not subscriptable error even though proper conversions have been made?

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.

error defining a string

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)

Using a calculation and a string in an input. (Python 2.7)

I'm having this annoying problem in Python 2.7, it won't let me do this
numbers = raw_input(numbers + 1 + ': ')
I want it to print out 'numbers + 1' as a number in the console but..
It comes up with this error message:
Traceback (most recent call last):
File "F:/Python/Conversation", line 25, in <module>
numbers = raw_input(numbers + 1 + ': ')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Is there a solution or just another thing that I can use instead of this?
Thanks in advance!
As the error message points out, you cannot add a number and a string. You can add two strings, so try this:
raw_input( str(numbers+1) + ':' )
You need to put + and numbers inside a single/double quote; or else, it will be treated as a string concatenation. You got the error because you tried to concatenate/add numbers with 1.
So, you need to cast 1 to a string, using str( ). Then, concatenate it with 'numbers + ' and ':'. Like so:
>>> numbers = raw_input('numbers + ' + str(1) + ': ')
numbers + 1:
However, If you want to replace numbers with number:
>>> numbers = 3
>>> numbers = raw_input(str(numbers + 1) + ': ')
4:
It works because you add the numbers's value with 1 first. Then, cast the result to string later.
You need to turn the 1 int value into a string:
numbers = raw_input(numbers + str(1) + ': ')
Alternatively, use string formatting:
numbers = raw_input('{}{}: '.format(numbers, 1))
Or perhaps you wanted to turn numbers into an int first, then the result into a string:
sum = int(numbers) + 1
numbers = raw_input(str(sum) + ': ')

Categories

Resources