Does string formatting not work within an input() function? - python

My code:
new_account = sys.argv[1]
confirm_new = input("Would you like to add {} to the dictionary?" +
"\ny or n\n".format(new_account))
This doesn't format the string to place the variable in place of {}. What's up?

This has nothing to do with input. It's just that addition has lower precedence than method calls:
>>> "{}" + "b".format('a')
'{}b'
Normally I just use automatic string concatenation if I have a multi-line string (just omit the +):
confirm_new = input("Would you like to add {} to the dictionary?"
"\ny or n\n".format(new_account))

Related

Removing strings character with given input

I need to remove a certain string with the given input. For example,
user_input = input("Input File name: ")
and the user key in "patient_zero[20150203].txt" and it would like to clean up the file name by removing all instances of square brackets and the contents contained within it.
Output should be "patient_zero.txt". Is there anyway to do it?
If you just want to remove the square bracket portion of the filename, you could use:
inp = "patient_zero[20150203].txt"
output = re.sub(r'^(\S+)\[.*?\]\.(\S+)$', r'\1.\2', inp)
print(output) # patient_zero.txt
using spplit
var = "patient_zero[20150203].txt"
print(var.split("[")[0] + var.split("]")[1]) # PatientName + FileFormat
import re
s = "patient_zero[20150203].txt"
print (re.sub(r'\[[\w\s]+\]','',s))
Output:
patient_zero.txt

Parameters feeding input variables in Python

Beginning Python guy here. Have some code I need help with.
My main question here is in this bit of code we have 3 define statements for mm, yy, and yyyy.
In the 'hpds_folder =' statement it references 'dnb*{0}{1}' with the {0} and {1} being the 1st and 2nd input parameters.
mm = hadoop.date_part()['mm']
yy = hadoop.date_part()['yy']
yyyy = hadoop.date_part()['yyyy']
hdfs_folder = '/sandbox/US_MARKETING/COMMON_DATA/BAU/FILES/{0}/{1}'.format(yyyy, mm)
find_dnb = hadoop.file_find(file='dnb*{0}*{1}*'.format(mm, yy), folder = hadoop._xfer_in_hadoop['dnb'])
print('dnb*{0}*{1}*')
I'm assuming {0} and {1} should be what are populated by mm and yy respectively.
But when I try to print out the string for it:
print('dnb*{0}{1}')
I get just the literal 'dnb*{0}{1}' as output.
Shouldn't I get a month and a year?
On your print statement, you didn't format the text, so it wasn't replaced. the assignment on file happened once and didn't change the string literal for other locations.
Therefore, your print should be formatted as well:
print('dnb*{0}*{1}*'.format(mm, yy))
In Python3.6+, a new formatted strings were introduced, letting you do things such as:
print(f'dnb*{mm}*{yy}*')
Notice the f before the string mark. fstrings let you inject code to the string inside curly brackets {}.
You can also use it on your find_dnb line:
find_dnb = hadoop.file_find(file=f'dnb*{mm}*{yy}*', folder = hadoop._xfer_in_hadoop['dnb'])

I'm getting a typeError: string indices must be integers, not type [duplicate]

This question already has answers here:
I'm getting a TypeError. How do I fix it?
(2 answers)
Closed 6 months ago.
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
def encode():
alpha[""] = key["x"]
def decode():
key[""] = alpha[""]
def menu():
response = raw_input("""Crypto Menu
quit(0)
encode(1)
decode(2)""")
return response
def main():
keepGoing = True
while keepGoing:
response = menu()
if response == "1":
plain = raw_input("text to be encoded: ")
print encode()
elif response == "2":
coded = raw_input("code to be decyphered: ")
print decode()
elif response == "0":
print "Thanks for doing secret spy stuff with me."
keepGoing = False
else:
print "I don't know what you want to do..."
print main()
I keep getting a TypeError saying string indices must be integers, not type. Not sure how to correct this, it is highlighting the decode and encode variables.
There's a lot going on here, but you're definitely having issues with your encode and decode functions. If I understand what you're trying to do, you could rewrite them as follows:
def encode(string):
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'XPMGTDHLYONZBWEARKJUFSCIQV'
encoded = []
for character in string:
character_index = alpha.index(character)
encoded.append(key[character_index])
return ''.join(encoded)
def decode(string):
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'XPMGTDHLYONZBWEARKJUFSCIQV'
decoded = []
for character in string:
character_index = key.index(character)
decoded.append(alpha[character_index])
return ''.join(decoded)
Each function is doing essentially the same thing (here's what encode is doing:
Creating an empty list called encoded. I'll use this to store each character, translated, in order.
Loop through the characters of the string passed in.
At each iteration, find its index in the string alpha.
Find the character in key at that same index and append that character to the list encoded
Once all the characters have been translated, join them into a string and return that string.
Note: This will fail if a character in the string argument is not found in the alpha string. You could add some error checking.
You could make this even more general if you wanted to allow for different keys. You could write a translate function like this:
def translate(string, from_language_string, to_language_string):
translated = []
for character in string:
character_index = from_language_string.index(character)
translated.append(to_language_string[character_index])
return ''.join(translated)
And then your encode and decode functions could be written like this:
def encode(string):
return translate(string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'XPMGTDHLYONZBWEARKJUFSCIQV')
def decode(string):
return translate(string, 'XPMGTDHLYONZBWEARKJUFSCIQV', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
To address what's going on in the rest of your code, for the conditionals in your main function, you'll just want to make sure to pass the strings read in from raw_input to the encode and decode functions as needed. Something like this:
if response == '1':
plain = raw_input('text to be encoded: ')
print encode(plain)
# and so on
Good luck.
I think your problem is here:
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
def encode():
alpha[""] = key["x"]
def decode():
key[""] = alpha[""]
I think you misunderstand how indexing in strings works. So let me try to correct this:
Take a string, like x = "hello". The reference x["h"] is meaningless. There's no way for Python to interpret this. On the other hand, x[0] is meaningful. It returns the element of x at index 0. That's "h", in our case.
Similarly, alpha[""] doesn't mean anything. When you use the square brackets, you are trying to specify an index in the string alpha. But the indices of alpha are integers. alpha[0] returns "A". alpha[1] returns "B". alpha[25] returns "Z".
So you need to use integers for your indices. Notation like key["x"] doesn't mean anything, and that raises errors.

replacing text in a file, Python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

concatenating string in python

I am converting a command line to a python string. The command line is:
../src/clus -INFILE=../input/tua40.sq -OUTPUT=OUT
The python statement is:
c_dir = '~/prj/clus/'
c_bin = c_dir + 'src/clus'
c_data = c_dir + 'input/tua40.sq'
c = LiveProcess()
c.executable = c_bin
c.cwd = c_dir
c.cmd = [c.executable] + ['-INFILE=', 'c_data, '-OUTPUT=OUT']
Problem is the c.cmd at the end looks like
~/prj/clus/src/clus -INFILE= ~/prj/clus/input/tua40.sq ...
Not that there is a 'space' after '=' which causes the program to report an error.
How can I concatenate '=' to the path?
LiveProcess is expecting an argv-style list of arguments. Where you want to make one argument, you need to provide one string. So use concatenation to make the string:
c.cmd = [c.executable] + ['-INFILE='+c_data, '-OUTPUT=OUT']
Also, no need for the list addition:
c.cmd = [c.executable, '-INFILE='+c_data, '-OUTPUT=OUT']
Why don't you just concatenate string like this:
a = 'A'+'B'
then
a == 'AB'
that is in your example
['-INFILE=' + c_data, '-OUTPUT=OUT']
Given that it looks like you're concatenating paths, you should be using os.path.join, not regular string concat.
Try this:
c.cmd = [c.executable] + ['-INFILE='+c_data, '-OUTPUT=OUT']

Categories