how do i remove comma in the list using for loop? - python-3.x

I have this code:
a = []
num = input('Enter numbers *Separate by using commas:')
for i in num:
a.append(i)
print(a)
and I get this:
Enter numbers *Separate by using commas:1,2,3
['1', ',', '2', ',', '3']
how do I remove the comma?..and I need to use the for loop...thanks

You can use this (by default prevents "," to enter in your array in the first place and functional for multi-digit numbers as you pointed out)-
a = []
num = input('Enter numbers *Separate by using commas:')
num = num.split(",") #splits the input string with "," delimiter
for i in num:
a.append(i)
print(a)

Related

Splitting a sequence of number into a list (Python)

I wanted to ask you how can I split in Python for example this string '20020050055' into a list of integer that looks like [200, 200, 500, 5, 5].
I was thinking about enumerate but do you have any example of a better solution to accomplish this example? thanks
One approach, using a regex find all:
inp = '20020050055'
matches = re.findall(r'[1-9]0*', inp)
print(matches) # ['200', '200', '500', '5', '5']
If, for some reason, you can't use regular expressions, here is an iterative approach:
inp = '20020050055'
matches = []
num = ''
for i in inp:
if i != '0':
if num != '':
matches.append(num)
num = i
else:
num = num + i
matches.append(num)
print(matches) # ['200', '200', '500', '5', '5']
The idea here is to build out each match one digit at a time. When we encounter a non zero digit, we start a new match. For zeroes, we keep concatenating them until reaching the end of the input or the next non zero digit.

How to convert an integer into a roman numeral?

I'm having trouble to make an integer into roman numeral for having an ouptut of integer with square brackets (I'm pretty sure it's a list, but what I want is to have an integer) and I couldn't find solution why I'm having 'None' on 'rom' value.
I'm using python3.
roman.py
#!/usr/bin/env python3
import sys
def numToRom(number):
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
num = sys.argv[1:]
rom = numToRom(num)
print(num, " is ", rom)
$ ./roman.py 2
Old output:
['2'] is None
Desired output:
2 is II
Your problem stems from the fact that you're passing a list with a character inside to your function. And that function expects an integer (if number in range(0, 9)), so you need to convert it to the right integer.
import sys
def numToRom(number):
if type(number) is list: # If you know your number might be a list with only one str(value)
number = int(number[0])
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
That will work specifically for your use case, if number is of the form ['{some digit}]. If you want to get fancier, you could use recursion to return a list with the roman number of each number in a list, like so:
def numToRom(number):
if type(number) is list:
rom = []
for value in number:
rom.append(numToRom(int(value)))
return rom
else:
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
>>> num = ['2', '3', '5']
>>> numToRom(num)
['2', '3', '5'] is ['III', 'IV', 'VI']
Note that this function works even if the values inside the input list are not characters, but normal integers.
>>> num = [2, 3, 5]
>>> rom = numToRom(num)
[2, 3, 5] is ['III', 'IV', 'VI']
pip install roman
import roman
print(roman.toRoman(int(input())))

What does int(n) for n mean?

In order to put the input into a list:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Can someone explain what does 'int(n) for n in' mean?
How do I improve this question?
The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Given your code:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Lets say you run the code provided, you get a prompt for input:
Enter numbers: 10 8 25 33
Now what happens is, Python's input() function returns a string, as documented here:
https://docs.python.org/3/library/functions.html#input
So the code has now essentially become this:
numbersList = [int(n) for n in "10 8 25 33".split()]
Now the split() function returns an array of elements from a string delimited by a given character, as strings.
https://www.pythonforbeginners.com/dictionary/python-split
So now your code becomes:
numbersList = [int(n) for n in ["10", "8", "25", "33"]]
This code is now the equivalent of:
numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
numberList.append(int(n))
The int(n) method converts the argument n from a string to an int and returns the int.
https://docs.python.org/3/library/functions.html#int
For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']
int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.
let us try to understand this list comprehension expression though a simple piece of code which means the same thing.
nums = input('Enter numbers: ') # suppose 5 1 3 6
nums = nums.split() # it turns it to ['5', '1', '3', '6']
numbersList = [] # this is list in which the expression is written
for n in nums: # this will iterate in the nums.
number = int(n) # number will be converted from '5' to 5
numbersList.append(number) # add it to the list
print(numbersList) # [5, 1, 3, 6]

Adding an x in front of and after words in a list

It's basic as far as Python goes, but I need to create a function List of words as an input parameter and outputs them as a single String formatted as a sentence with a period at the end and lower case 'x's around each word.
e.g.
Input: ["This", "is", "a", "sentence"]
Returns: "xThisx xisx xax xsentencex.
I think I need a for loop, but I keep getting errors in trying them.
Thanks in advance!
The closest I've come is through:
quote = ["This","is","a","sentence"]
def problem3(quote):
blue='x x '.join(quote)
return(blue)
which returns "Thisx x isx x ax x sentence"
quote = ["This","is","a","sentence"]
s = ""
for word in quote:
s = s + "x" + word + "x "
s = s[:-1]
print(s)
Out[17]: 'xThisx xisx xax xsentencex'
list_ = ["This", "is", "a", "sentence"]
string =''
for item in list_:
string += ' x' +item+'x'
string = string.strip()
print(string)
Map the initial list
>>> list_ = ["This", "is", "a", "sentence"]
>>> newlist = list(map(lambda word: f"x{word}x", list_))
>>> print(newlist)
['xThisx', 'xisx', 'xax', 'xsentencex']
And then reduce it to get the complete sentence
>>> import functools
>>> result = functools.reduce(lambda a,b : f"{a} {b}", newlist2)
>>> print(result)
xThisx xisx xax xsentencex

Reordering character triplets in Python

I've been trying to solve this homework problem for days, but can't seem to fix it. I started my study halfway through the first semester, so I can't ask the teacher yet and I hope you guys can help me. It's not for grades, I just want to know how.
I need to write a program that reads a string and converts the triplets abc into bca. Per group of three you need to do this. For examplekatzonbecomesatkonz`.
The closest I've gotten is this:
string=(input("Give a string: "))
for i in range(0, len(string)-2):
a = string[i]
b = string[i + 1]
c = string[i + 2]
new_string= b, c, a
i+=3
print(new_string)
The output is:
('a', 't', 'k')
('t', 'z', 'a')
('z', 'o', 't')
('o', 'n', 'z')
The code below converts for example "abc" to "bca". It works for any string containing triplets. Now, if input is "abcd", it is converted to "bcad". If you input "katzon", it is converted to "atkonz". This is what I understood from your question.
stringX = input()
# create list of words in the string
listX = stringX.split(" ")
listY = []
# create list of triplets and non-triplets
for word in listX:
listY += [[word[i:i+3] for i in range(0, len(word), 3)]]
# convert triplets, for example: "abc" -> "bca"
for listZ in listY:
for item in listZ:
if len(item)==3:
listZ[listZ.index(item)] = listZ[listZ.index(item)][1:] + listZ[listZ.index(item)][0]
listY[listY.index(listZ)] = "".join(listZ)
# create final string
stringY = " ".join(listY)
print(stringY)

Resources