New line character as user input in Python - python

While joining items in a list and printing them out as a string, I wanted to take user input for a character that will be used a separator. What if the separator is to be a newline? What can the user input be? Because if the user input is simply '\n' then that is being used literally ('\n' is being added as text).
Code that I ran:
tojoin = ['Hello','Its','Me','Uh','Mario']
merge = tojoin[0]
sepchar = input("Enter the character(s) with which you wish to separate the list items: ")
#User input = '\n'
for i in tojoin:
merge = merge+sepchar+i
print(merge)
Expected output:
Hello
It's
Me
Uh
Mario
Actual output:
Hello\nHello\nIts\nMe\nUh\nMario
How can I get to the expected output?

you need to add the following line of code after the input
sepchar = bytes(sepchar, "utf-8").decode("unicode_escape")
source

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

How to print multiple values from for loop inside print statement in a single line?

My Code has something like:
user = input("Enter username: ")
I have 10 variables like:
ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
...
Suppose username entered is Pawan my input statement returns me a list:
basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')
The output is some random numbers from 1 to 10 in a list:
['1','3','7']
Now I want to print a single string in a single line based on the choices of user:
For 1,3,7 is should give the output:
The strings selected by you are String1; String3; String7; in the strings list of Pawan
(semicolon should be included)
I have tried many ways but it doesn't work, either returns the value of only 1st number or it returns the generator object at address
print("The strings selected by you are ch{0}; in the strings list of {1}".format(*basic_choices, user))
print("The strings selected by you are ch{0}; in the strings list of {1}".format(choice, user) for choice in basic choices)</p>
I think it would make sense to just put your "Strings" in a dictionary, where the keys are the possible user inputs. I then used str.join to format the output correctly:
user = 'Pawan'
ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
ch5 = "String5"
str_options = {'1':ch1,'2':ch2,'3':ch3,'4':ch4,'5':ch5}
basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')
chosen = [str_options[i] for i in basic_choices]
print("The strings selected by you are " +
"; ".join(chosen) +
"; in the strings list of {}".format(user))
Note that (as is) this will raise an error if the user input is not in the dicitionary.

Print specified output in subrocess

I want to print specified output in subrocess
Here is my code:
from subprocess import check_output
output = check_output(['python3', 'code.py']).decode('ascii')
print(output)
The output is:
Tom
John
How can I print just Tom or just John instead of both of them?
I have tried print(output[0]) to print Tom but I get only T.
You have single string and you can use any string's function.
You can split it and create list with lines
lines = output.split('\n')
And then display only first line
print(lines[0])
Let's take a look on steps you've already done:
You call check_output() and it returns output in the form of bytes;
Then You call bytes.decode(), which returns str.
As a result you get multi-line string. You've tried to access to first line using index 0, but you got first char instead of first line. It happened, cause accessing to string by index will return you char from this index.
To get first line you should split lines of your multi-line string (convert str to list of str). There's built-in function str.splitlines() which does what you need.
So, to upgrade your code we need to add one more line before your print() statement:
output_lines = output.splitlines()
After that you can access to line by index:
print(output_lines[0])

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

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.

Categories