Can't convert 'list' object to str implicitly python - python

elif used_prefix and cmd == "xp":
if self.getAccess(user) >= 1:
f = open("users/" + user.name.lower() + ".txt", 'r')
word = f.readline().split("X Points = ")
if word == "0":
room.message("You have no X Points")
else:
room.message("You Have " + word + " X Points")
f.close()
else:
room.message("You are not whitelisted " + user.name.capitalize())
When I try to use XP it shows Can't convert 'list' object to str implicitly as the error in the console. I'm using python 3.3.

You might need
word = f.readline().split("X Points = ")[1].strip()
as you are splitting, it will return the list of items split as a list. You need to take the element corresponding to the actual value
Example
data = "X Points = 10"
print data.split("X Points = ")
Output
['', '10']
So, we need to get the second element. Thats why we use [1]

The main issue is that split returns a list, not a string.
if self.getAccess(user) >= 1:
with open("users/{}.txt".format(user.name.lower()), 'r') as f:
word = f.readline().split("X Points = ")[1]
if word == "0":
room.message("You have no X Points")
else:
room.message("You Have {} X Points".format(word))
else:
room.message("You are not whitelisted {}".format(user.name.capitalize()))

Related

input is not changing in iteration

In the code below, I am trying to input the number (e.g. 2 3 4). Suppose if the length of the input is not equal to mat_dim_col, I want to input again. However, the function is retaining the previous input and not returning the latest one.
Matrix row entry function.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
mat_row(mat_dim_col,r)
When you recurse, you need to return the value it provides, otherwise, you might end up getting a correct response after a few attempts but it won't be returned through the stack correctly.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
""" RETURN mat_row response """
return mat_row(mat_dim_col,r)

Removing extra whitespace between words using for loop Python

I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.

TypeError: can only join an iterable python

I'm trying to insert delimiters into a string that was created by a previous function (ifw(in_list)). I'm not having any issues with \n or \t but once my code gets to "," join it breaks down. I've tried a few different solutions and looked through similar questions/answers on the site but I keep getting the TypeError: can only join an iterable. Any help you can provide me would be very apprciated.
#! /usr/bin/env python
import os
import sys
import re
delim = os.getenv("QWIKIFWLISTMGR_DELIMITER")
in_list = sys.argv
def delim(in_list):
x = "screw python"
x = os.getenv('QWIKIFWLISTMGR_DELIMITER')
if 'BLANK' in x:
x = ' '.join(ifw(in_list))
return x
elif 'TAB' in x:
x = ifw(in_list)
x = '\t'.join(x)
return x
elif 'NL' in x:
x = ifw(in_list)
x = '\n'.join(x)
return x
elif 'COMMA' in x:
x = ','.join(str(x) for x in (ifw(in_list)))
return
elif 'COLON' in x:
x = ifw(in_list)
x = ':'.join(x)
return x
elif 'SEMICOLON' in x:
x = ifw(in_list)
x = ';'.join(x)
return x
elif 'SLASH' in x:
x = ifw(in_list)
x = '/'.join(x)
return x
else:
x = ifw(in_list)
return
def ifw(in_list):
usr_choice = (in_list)[1]
if usr_choice == 'i':
print(int_sort(in_list))
elif usr_choice =='f':
print(float_sort(in_list))
elif usr_choice == 'w':
print(word_sort(in_list))
def float_sort(in_list):
float_sort = "test"
sorted_float = "test"
float_sort = in_list[2:]
float_sort = ''.join(float_sort)
#float_sort1 = " ".join(list((re.findall(r"((?<!\S)\d+(?!\S))", float_sort))))
#float_sort2 = ' '.join(list(re.findall(r"(\d+\.\d+)", float_sort)
float_sort = " ".join(re.findall(r"\d*\.\d+|\d+", float_sort))
sorted_float = sorted(float_sort, key=len)
return float_sort
#print (float_sort(in_list))
def word_sort(in_list):
word_sort = " 1a "
word_sort = sorted(in_list[2:], key=len) #in_list must be 2 because the program will view usr input as a word
for i in word_sort:
punctuation = '.',',',';','!',' / ','"','?' #strips punctuation from words
if i in punctuation: #removes punctuation
word_sort = word_sort.replace(i," ")
#word_sort= sorted(word_sort, key=lambda L: (L.lower(), L))
word_sort= " ".join(sorted(word_sort, key=lambda L: (L.lower(), L))) #takes string and sorts by length giving priority to upper over lower when tied
sorted_word = " 1a " #left for testing
sorted_word = re.sub("\S+\d\S+", "", word_sort).strip() #removes any word with a number in it
sorted_word = "".join(sorted_word) #joins the results back into a string
return sorted_word
def int_sort(in_list):
in_list = " ".join(in_list[1:]) # takes information from argv and creates a string with it
int_sort = " ".join(list(reversed(re.findall(r"(?<!\S)\d+(?!\S)", in_list))))
# find all looks for a pattern of anything but a space... any number. anything besides a space in the in_list and returns it
#reveresd flips that return backwards
# list turns that into a list and join makes it a string again
return int_sort
#print int_sort(in_list)
#print (delim(in_list))
Your ifw function has no return statement, so it returns None.
So the line:
x = ','.join(str(x) for x in (ifw(in_list)))
becomes
x = ','.join(str(x) for x in None)
and python can't iterate over None.

List prints square brackets in python 2.7

import sys
import string
import re
keywords = []
task = "*"
while task not in "ed":
task = raw_input("Encrypt or Decrypt: \nType ‘e’ to Encrypt\nType ‘d’ to Decrypt\n").lower()
keyword = "*"
keyphrase = "*"
while not(re.match('[a-z ]+$',keyword)):
keyword = raw_input("enter your first keyword:-").lower()
while not(re.match('[a-z ]+$',keyphrase)):
keyphrase = raw_input("enter a key phrase:-").lower()
loop = 0
repeated_keyword = ""
if len(keyword) < len(keyphrase):
while len(repeated_keyword) < len(keyphrase):
repeated_keyword = repeated_keyword + keyword[loop]
loop += 1
if loop >= len(keyword):
loop = 0
elif len(keyword) == len(keyphrase):
repeated_keyword = keyword
last_charecter_in_keyword = keyword[-1]
elif len(keyword) > len(keyphrase):
repeated_keyword = keyword
last_charecter_in_keyword = keyword[-1]
while len(repeated_keyword) > len(keyphrase):
repeated_keyword = repeated_keyword[:-1]
repeated_keyword_letter_positions = []
keyphrase_letter_positions = []
for character in repeated_keyword:
position_of_char_in_repeated_keyword = (string.ascii_lowercase + " ").find(character) +1
repeated_keyword_letter_positions.append(position_of_char_in_repeated_keyword)
for character in keyphrase:
position_of_char_in_keyphrase = (string.ascii_lowercase + " ").find(character)
keyphrase_letter_positions.append(position_of_char_in_keyphrase)
if task == "e":
final_positions_of_letters = [a + b for a, b in zip(keyphrase_letter_positions,repeated_keyword_letter_positions)]
elif task == "d":
final_positions_of_letters = [a - b for a, b in zip(keyphrase_letter_positions,repeated_keyword_letter_positions)]
new_letter = ""
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher = str(final_cipher) + str(new_letter)
loop += 1
print final_cipher
This is a encryption/ decryption programme in python 2.7. However at the end of the programme when the final_cipher list is printed to the shell a pair of [] brackets are printed prior to the contents of the list
You have some options here:
• Loop through the array, and print each element on the same row without delimiter.
• Use 'join' to join all the parts of the array in a single string. You can find more information about the join statement here.
Personally I do think 'join' is the best option here.
I guess you are trying to output a string. And you are making a mistake by setting the initial declaration to an empty list.
For fixing this just use :
final_cipher = "" instead of final_cipher = []
This should get you the output in string format.
Seeing:
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher = str(final_cipher) + str(new_letter)
loop += 1
print final_cipher
I see that you are working with final_cipher like a string, then you should initialize like:
final_cipher = ""
And:
final_cipher = str(final_cipher) + str(new_letter)
Should be:
final_cipher = final_cipher + str(new_letter)
Or better:
final_cipher += str(new_letter)
final_cipher is a list, so yes, printing it will print it as a string, i.e. the result of calling str(final_cipher).
If you want to just print the elements seperated by a comma, you can use .join:
print ", ".join(final_cipher)
You create final_cipher as a list but then change your mind and do string concatenation instead. On the first iteration of the loop, str(final_cipher) creates the string representation of an empty list "[]". Look familiar? Keep a list and build the string at the end.
final_cipher = []
loop = 0
alphabet = string.ascii_lowercase + " " + string.ascii_lowercase + " "
while loop < len(final_positions_of_letters):
new_letter =alphabet[final_positions_of_letters[loop]]
final_cipher.append(str(new_letter))
loop += 1
final_cipher = ''.join(final_cipher)
print final_cipher

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories