This question already has answers here:
Convert string to variable name in python [duplicate]
(3 answers)
Closed 4 years ago.
I want to print variables vector1 and vector2 in Python 3, without having to write the print code manually. How can I do this? Below you can see the code that I tried using for this.
vectorInput = input("Enter vectors values separated by ',' and vectors separated by ' ': ")
vector1,vector2 = vectorInput.split(" ")
for num in range(1,3):
print({}.format('vector'+num))
Thank you.
Well, you can use comprehensions directly.
[print(i) for i in vectorInput.split(" ")]
Or use list of vectors, as it more fits in your usage pattern, and ou can reuse it later.
vectors = vectorInput.split(" ")
[print(i) for i in vectors]
Or with for
vectors = vectorInput.split(" ")
for i in vectors:
print(i)
This is the shorter version give a try.
for i in input("Enter vectors values separated by ',' and vectors separated by ' ': ").split():
print(f'vector {i}')
If you want i as an integer then replace i with int(i)
Related
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I am currently doing a task but I am stuck at the moment, so here is the code so far I have written:
string = input('please enter a string: ')
s = []
def sentenceCapitalize(string):
strn = string.split('. ') #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:].lower()
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)
It only gets me the result as a list and period is disappeared
Unexpected Output:
Expected Output:
Hello. My name is Joe. What is your name?
And here is the question from the book:
Write a program with a function that accepts a string as an argument
and returns a copy of the string with the first character of each
sentence capitalized. For instance, if the argument is “hello. my name
is Joe. what is your name?” the function should return the string
“Hello. My name is Joe. What is your name?” The program should let the
user enter a string and then pass it to the function. The modified
string should be displayed.
Can you fix this solution? thanks.
The main three errors you have in your code are:
You convert to lower case the rest of the sentence, so for example Joe will become joe
You split based on ('. '), but when concatenating back you join by ('.'), so you are missing the white space
You need a regex split, to consider both , and .. In the regex you pass the two options separated by |, and for the case of dot you need to add before '' since '.' itself is an operator in regex. More about Regular Expression
Try this:
string = input('please enter a string: ')
s = []
import re
def sentenceCapitalize(string):
strn = re.split(',|\.', string) #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:]
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)
One sentence solution:
print('. '.join([st[0].upper() + st[1:] for st in string.split('. ')]))
This question already has answers here:
Print without space in python 3
(6 answers)
Closed 2 years ago.
So whenever I try to run this function there is a space between the two values i want to print can anyone help?
def initials():
dot = "."
f = input("first name: ")
s = input("last name: ")
print(f[0],dot,s[0])
initials()
A trailing comma will result in another space to be appended, but not with '+' operator.
This question already has answers here:
Print a list of space-separated elements
(4 answers)
Closed 2 years ago.
Hi: I am new to python and programing.
I have a silly question that I couldn't solve.
a=[1,2,3,4,5]
for i in a:
print(i,end=' ')
will get a out put:
1 2 3 4 5
There are space between each numbers in the system out print: ( s means space)
1s2s3s4s5s
How can I remove the last space? The correct out put will be :
1s2s3s4s5
a=[1,2,3,4,5]
print(' '.join([str(x) for x in a])
This will first convert each element of 'a' to string and then join all element using join(). It must be noted that ' ' can be replaced with any other symbol as well
There are various ways, but a simple way is join:
print(' '.join(a), end='')
You can also directly use print:
print(*a, sep=' ', end='')
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'.
My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.
So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.
def listToString(aList):
newString = ''
for i in range(len(aList) - 1):
newString += aList[i] + ', '
newString = newString + 'and ' + aList[-1]
return(newString)
spam = list(input())
print(listToString(spam))
input() always gives you just a string.
You can analyze that string depending on how the user is supposed to enter the list.
For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do
input_list = input().split()
print(listToString(input_list))
You can also split on , or any delimiter you like.
If you want to read a list literal from user input, use ast.literal_eval to parse it:
import ast
input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
You could build a list from the input and use your current working code to format it as you want.
def get_user_input():
my_list = []
print('Please input one word for line, leave an empty line to finish.')
while True:
word = input().strip()
if word:
my_list.append(word)
else:
break
return my_list
I'm trying to write a program that uses Pascal's triangle to FOIL binomials. Any binomial FOILed using this method will follow a basic pattern. I already have a general idea of what to do, I just need to figure out how to separate a space-delimited string into many ints that are called by variables.
For example, I want to take this input:
pascalInput = raw_input("Type the full row of Pascal's triangle with numbers separated by space: ")
#say the input is '1 3 3 1'
and put it into the variables:
pascalVal1
pascalVal2
pascalVal3
etc.
I don't know how I would write out how many variables I need or whatever else.
It would be more convenient if you stored your values in a list:
pascalVals = raw_input('...').split()
And then access them like this:
pascalVals[0]
pascalVals[1]
pascalVals[2]
If you want integers instead of strings, use:
pascalVals = [int(x) for x in raw_input('...').split()]
pascalVals = PascalInput.split(' ')
pascalVals - list of strings. For indexing write
some_var = pascalVals[0]
If you need exactly pascalVal1 vars:
for i in len(pascalVals):
exec('pascalVal' + str(i+1) + ' = pascalVals[' + str(i) + ']')
use map function
print map(int, raw_input("Type the full row of Pascal's triangle with numbers separated by space: ").split())