How do I convert user input into a list? [duplicate] - python

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 4 months ago.
I'm wondering how to take user input and make a list of every character in it.
magicInput = input('Type here: ')
And say you entered "python rocks"
I want a to make it a list something like this
magicList = [p,y,t,h,o,n, ,r,o,c,k,s]
But if I do this:
magicInput = input('Type here: ')
magicList = [magicInput]
The magicList is just
['python rocks']

Use the built-in list() function:
magicInput = input('Type here: ')
magicList = list(magicInput)
print(magicList)
Output
['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']

It may not be necessary to do any conversion, because the string supports many list operations. For instance:
print(magicInput[1])
print(magicInput[2:4])
Output:
y
th

Another simple way would be to traverse the input and construct a list taking each letter
magicInput = input('Type here: ')
list_magicInput = []
for letter in magicInput:
list_magicInput.append(letter)

or you can simply do
x=list(input('Thats the input: ')
and it converts the thing you typed it as a list

a=list(input()).
It converts the input into a list just like when we want to convert the input into an integer.
a=(int(input())) #typecasts input to int

using list comprehension,
magicInput = [_ for _ in input("Enter String:")]
print('magicList = [{}]'.format(', '.join(magicInput)))
produces
Enter String:python rocks
magicList = [p, y, t, h, o, n, , r, o, c, k, s]
You can use str.join() to concatenate strings with a specified separator.
Furthermore, in your case, str.format() may also help.
However the apostrophes will not interfere with anything you do with the list. The apostrophes show that the elements are strings.
Method 2:
magicInput = ','.join(input('Enter String: '))
print(f'\nmagicList: [{magicInput}]')

Related

How do I change letters in this list in python?

So I'm trying to make a program that allows you to decode messages in python. Here's what I got so far...
def decode():
print("Let's see what she wanted to tell you.")
time.sleep(2)
messageOne= raw_input('Please paste the message: ')
print("Decoding message now...")
message= list(messageOne)
and I was wondering how I would take the individual letters in the list and change them based on the code I want. Aka I need to know how to change a specific value in the list. Thanks!
Your question isn't very clear, based on what I see you can have different ways of replacing letters. For example let's use string s:
>>> s = 'Hello'
>>> s.replace('l','h')
Hehho
If you only want to replace one occurrence of a given letter use this:
>>> s = 'Hello'
>>> s.replace('l','h', 1) #will only replace the first occurrence
Hehlo
You can also convert your string into a list
>>> s = 'Hello'
>>> s = [x for x in s]
>>> s
['H', 'e', 'l', 'l', 'o']
In here you can replace anything by anything, like so:
>>> s[3] = 'h'
>>> s
['H', 'e', 'l', 'h', 'o']
When you're done with replacing whatever you want, you can use the .join() method to make your list a string again like so:
>>> s = ''.join(s) #separator goes in between the quotes
>>> s
Helho

Replacing a character from a certain index [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
How can I replace a character in a string from a certain index? For example, I want to get the middle character from a string, like abc, and if the character is not equal to the character the user specifies, then I want to replace it.
Something like this maybe?
middle = ? # (I don't know how to get the middle of a string)
if str[middle] != char:
str[middle].replace('')
As strings are immutable in Python, just create a new string which includes the value at the desired index.
Assuming you have a string s, perhaps s = "mystring"
You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.
s = s[:index] + newstring + s[index + 1:]
You can find the middle by dividing your string length by 2 len(s)/2
If you're getting mystery inputs, you should take care to handle indices outside the expected range
def replacer(s, newstring, index, nofail=False):
# raise an error if index is outside of the string
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
# if not erroring, but the index is still not in the correct range..
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
# insert the new string between "slices" of the original
return s[:index] + newstring + s[index + 1:]
This will work as
replacer("mystring", "12", 4)
'myst12ing'
You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.
>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'
Strings in Python are immutable meaning you cannot replace parts of them.
You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.
You could for instance write a function:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
And then for instance call it with:
new_string = replace_str_index(old_string,middle)
If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.
For instance:
replace_str_index('hello?bye',5)
will return 'hellobye'; and:
replace_str_index('hello?bye',5,'good')
will return 'hellogoodbye'.
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]
# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]
I/P : The cat sat on the mat
O/P : The cat slept on the mat
You can also Use below method if you have to replace string between specific index
def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos,endPos):
singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
return singleLine

how can i change string using for-loop without regex in python [duplicate]

This question already has answers here:
Elegant Python function to convert CamelCase to snake_case?
(30 answers)
Closed 6 years ago.
how can i change string using for-loop without regex.
example : (python 2.7.1)
import re
trans = lambda src: re.sub("([A-Z])", lambda m:"_"+m.group().lower(), src, flags=0)
print(trans("helloWorld"))
i expect to result as :
hello_world
i want to change from regex version into for-loop version.
conditions
the result will be the same
just one line!
using for loop
def change(string):
for letter in string:
if letter.isupper():
yield '_{}'.format(letter.lower())
else:
yield letter
print ''.join(change("helloWorld"))
If you want to have it in one line:
print ''.join(letter.isupper() and '_{}'.format(letter.lower()) or letter for letter in 'helloWorld')
You may achieve it using list comprehension (i.e one liner for loop) as:
>>> my_string = "helloWorld"
>>> ''.join(['_{}'.format(s.lower()) if s.isupper() else s for s in my_string])
'hello_world'
Explanation:
List is nothing but a list of chars. Iterate over each char and check whether it is upper case character using isupper() fuct. If it is, replace it to _<lower-case> using lower() func.
The result of above list comprehension is: ['h', 'e', 'l', 'l', 'o', '_w', 'o', 'r', 'l', 'd']. Join the list to find your string i.e. hello_world

Separating a list into two - Python [duplicate]

This question already has answers here:
How can I partition (split up, divide) a list based on a condition?
(41 answers)
Closed 9 years ago.
For the following code:
print("Welcome to the Atomic Weight Calculator.")
compound = input("Enter compund: ")
compound = H5NO3
lCompound = list(compound)
I want to create two lists from the list lCompund. I want one list for characters and the other for digits. So that I may have something looking like this:
n = ['5' , '3']
c = ['H' , 'N' , 'O']
Can somebody please help by providing a simple solution?
Use a list comprehension and filter items using str.isdigit and str.isalpha:
>>> compound = "H5NO3"
>>> [c for c in compound if c.isdigit()]
['5', '3']
>>> [c for c in compound if c.isalpha()]
['H', 'N', 'O']
Iterate the actual string only once and if the current character is a digit, then store it in the numbers otherwise in the chars.
compound, numbers, chars = "H5NO3", [], []
for char in compound:
(numbers if char.isdigit() else chars).append(char)
print numbers, chars
Output
['5', '3'] ['H', 'N', 'O']

Python: Problem with raw_input, turning the value I get into an array

I'm having issues with raw_input again, this time trying to turn the value I get into a list. Here is my code:
original = raw_input("Type is your input? ")
original_as_array = list('original')
print original_as_array
for i in range(0,len(original)):
print i
my print original_as_array literally prints ['o', 'r', 'i'.... etc]. If we pretend that my input is Hello World, I want original_as_array to output: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o'... etc]. I think I'm making a tiny mistake. Can you point me in the right direction:)?
Quotes form a string literal.
original_as_array = list(original)
original = raw_input("Type is your input? ")
original_as_array = list(original) # no quotes. If you put quotes, you are turning it into a string.
print original_as_array
for i in original_as_array: # this is shorter way to iterate and print than your method
print i
Strings are already iterable, so you don't need to convert it to a list, so you can easily go :
original = raw_input("Type is your input? ")
# or if you really want a list
original_as_list = list(original) # NOT 'original', that's passing the string original not the value of original
for letter in original:
print letter

Categories

Resources