Splitting String Variable Into New Variables - python

I am creating a script that splits the user input into letters, I have gotten this part down, however, how do I turn these separated letters into individual variables?
message = input("Enter Message) ")
list = list(message)
print(list)
Whilst this does print out the typed string into letters, I want to know how to turn those split letters into their own variables. e.g (h, e, l, l, o) Is there a way that I can, for example, only print the first letter or the second letter? (so that the letters are split into their own variables)

You can treat the list as a set 'own variables' (accessing them by index).
message = input("Enter Message) ")
l = list(message) # do not use reserved words, as 'list' for variable names
print(l)
print(l[0]) # prints the 1st letter
print(l[1]) # prints the 2nd letter
print(l[-1]) # prints the last letter
print(l[-2]) # prints the letter prior to the last

Just adding some examples:
message = input("Enter Message) ")
message_characters = list(message) # do not use single characters as variable names
for i, char in enumerate(message_characters):
print(f'The {i}{"th" if i>2 or i==0 else "nd" if i==2 else "st"} character is {char}')
# Though note that strings are also iterable:
for i, char in enumerate(message):
print(f'The {i}{"th" if i>2 or i==0 else "nd" if i==2 else "st"} character is {char}')

Related

Count characters in user input, if not divisible by three, then trim excess characters

Just getting started learning Python and have a question. Given a user input of a DNA sequence that can be any number of characters long, how would I go about printing a result that trims excess characters from the end of the string and returns a result?
Example: user inputs a DNA sequence of "ACG CTA TCG C".
The desired result would be "ACG CTA TCG" (groups of 3, excess trimmed from result). If the user input was "ACC TAG TAG AT," the result would be "ACC TAG TAG". And so on with any input the user enters.
Here's what I have so far:
# Request user input, convert to uppercase and remove white spaces
dna_input = input("Enter a DNA sequence: ").upper()
dna_input = dna_input.replace(" ", "")
# Empty variable to hold reading frame result
reading_1 = ""
chars = 0
# Check that input is valid - only contain letters A, C, G, T
if set(dna_input) <= {"A", "C", "T", "G"}:
# First reading frame
# Return codons in order, trim excess
chars = len(dna_input) # how many characters
if chars % 3 == 0: # check if chars are divisible by three
for j in dna_input:
reading_1 += j
print("First reading frame:", reading_1)
else:
print("Need to do something different. How to trim excess?")
# If invalid letters used, return error
else:
print("Try again using a valid input.")
I'm also getting a syntax error with the inner else statement and am not sure why...
I would just use a regular expression for this
[ACTG]{3} will match any sequence of length 3 using the characters {A,C,T,G}
and then " ".join() will join them together with a space in-between.
def trim_chain(chain):
print(" ".join(re.findall(r"[ACTG]{3}",chain)))
trim_chain("ABC ACT CTG TGG TC")
The problem is here print("First reading frame:", reading_1), this print has to be indented. This break the if/else logic.
# Request user input, convert to uppercase and remove white spaces
dna_input = input("Enter a DNA sequence: ").upper()
dna_input = dna_input.replace(" ", "")
# Empty variable to hold reading frame result
reading_1 = ""
chars = 0
# Check that input is valid - only contain letters A, C, G, T
if set(dna_input) <= {"A", "C", "T", "G"}:
# First reading frame
# Return codons in order, trim excess
for i in range(len(dna_input)): # count characters
chars += 1
print("There are", chars, "characters.")
if chars % 3 == 0: # check if chars are divisible by three
for j in dna_input:
reading_1 += j
print("First reading frame:", reading_1)
else:
print("Need to do something different. How to trim excess?")
# If invalid letters used, return error
else:
print("Try again using a valid input.")
I hope I've helped!

String Index out of Range - Python 3.x.x with swapcase() function

I am trying to capitalize every other letter of a string which is given by and input. For some reason it give me the error 'string index out of range' and i have no idea why! the range is set from 0 to the length of the string so that cant be possible i thought!
s = input('Please enter a string: ')
p=s.lower()
o=s.upper()
q=p
k=len(s)
l=1
for x in range(0,k):
if l%2==0:
q=q[x].swapcase()
l+=1
else:
l+=1
print(q)
When you do this:
q=q[x].swapcase()
q becomes a single letter.
The next time around you try:
q[1]
but there is no q[1] because you made it a single letter.
This is one of several reasons why python encourages you to avoid creating index variables and instead looping over the items themselves. If you do that and give your variables more descriptive names, these kind of error are easier to catch. For example:
s = input('Please enter a string: ')
lower_case = s.lower()
new_string = ""
for index, letter in enumerate(lower_case):
if index % 2 == 0:
new_string += letter.swapcase()
else:
new_string += letter
print(new_string)

printing each letter of string same number of times as number of letters

I am trying to make this function so that it prints each letter of the string, the number of times the same of number of letters in the string. so for example if the string was 'hi' , then the output of the function would be:
hh
ii
(each letters on separate lines like above)
however my code only prints 'ii' for the above example and I don't quite know why.
def vertical_strings(string):
"""takes a string and prints each letter on new line repeating each letter for length of word"""
num = len(string)
for char in string:
new = char * num
return new
print(vertical_strings('hi'))
def vertical_strings(string):
"""takes a string and prints each letter on new line repeating each letter for length of word"""
num = len(string)
for char in string:
new = char * num
print new
vertical_strings('hi')
You just have to make minor tweaks in your code
Since you need to print, have the print on each iteration of the code
You're returning the result for last letter only, try using a list of all letters repeated instead, then join the list's elements by a newline (\n) character:
def vertical_strings(string):
num = len(string)
new = []
for char in string:
new.append(char * num)
return '\n'.join(new)
print(vertical_strings('hi'))
Output:
hh
ii
I think that there should also be a provision to capture unique letters only from the given string. My solution here emphasizes with a palindrome mom that there exists two unique character and there should be only two lines of output. Please check it out and give your feedback.
def vertical_strings(string):
return [x*len(string) for x in list(set(string))]
[print(x) for x in vertical_strings('mom')]
Output:
mmm
ooo

Why can't the index at which I want to replace a letter, be a variable in python?

So I have this assignment where I need to get a string from the user and then store that string as a list. The program will then ask the user for an index and a letter. The letter will then be replaced in their initial word at the given index.
This is how it should work:
Enter a word: cat
Enter an index: 1
Enter a letter: o
Your new word is: cot
I can ask and store the users responses with functions correctly but I have a problem joining the list with this code:
word_list[index] = (letter)
word_string = "".join(word_list)
print (word_string)
index and letter are the variables that the user input
For some reason, the program only returns the letter variable that the user entered. How do I replace the letter they give at the index they give, then return the whole list as a string?
Entire Code:
### function that replaces letters
### at specificed indices
# function that asks user for an index
def get_index():
while True:
try:
index = int(input("Enter an index (-1 to quit): "))
if index == -1:
quit
elif index < -1:
print ("Must be higher than -1!")
except ValueError:
print ("Enter a valid index!")
return index
# function that asks user for a letter
def get_letter():
while True:
try:
letter = input("Enter a lowercase letter: ")
if letter.isupper():
print ("Must be a lower case letter")
except ValueError:
print ("Enter a valid letter!")
return letter
# ask the user for a word
my_word = input("Enter a word: ")
# variable that holds current word as a list
my_word_list = list(my_word)
# call the function get_index() and store it as a variable called index1
index1 = get_index()
# call the function get_letter() and store it as a variable called letter1
letter1 = get_letter()
# print the word they entered as a list
print (my_word_list)
# insert their letter into the list at the index they gave
my_word_list[index1] = letter1
# turn the list into a string
my_word_string = "".join(my_word_list)
# print the final string
print (my_word_string)
This should work (for Python 3)
word = input("enter a word")
letter = input("enter a letter")
index = input("enter an index")
# type conversion
word_list = list(word) # as input always returns a string, and we can't modify a string
index = int(index)
# changing the list
word_list[index] = letter
# converting back the list to string
word = "".join(word_list)
print(word)
As Joe pointed out, strings are not mutable... but lists are. Although strings act like lists sometimes, they are not. If you explicitly make your word a list of characters, then you're example works.
word = input('word: ')
index = int(input('index: '))
letter = input('letter: ')
word_list = list(word)
word_list[index] = letter
new_word = "".join(word_list)
print(new_word)
The reason you cannot replace characters directly is due to the immutability of strings. I.e. you cannot change them. So the way to replace a character at an index is to take a slice up to that index and then concatenate the character and then finally concatenate the rest of the string.
This method can be seen here:
word = "cat"
index = 1
replacement = "o"
new_word = word[:index] + replacement + word[index+1:]
#new_word --> 'cot'

Python 3 - Creating a program inputing a list and printing the strings from it alphabetically

I'm working a question where I need to create a program that will ask the user to input a list and then it will print off the strings that start with letters A-I.
Question: Implement a program that asks for a list of student names from
the user and prints those names that start with letters A through I.
Create two test lists.
>>> phrase = input('Enter a list of Students: ')
Enter a list of Students: ['Albert', 'Ian', 'Bob', 'Dave', 'Edward']:
>>> for c in phrase:
if c in 'abcdefghiABCDEFGHI':
print(c)
Right now the print function results in:
A
b
e
I
a
B
b
D
a
e
E
d
a
d
It prints off letters in each of the name in alphabetical order, but what I want it do do is print off the entire names in alphabetical order. Once I can do it for one list, a 2nd list shouldn't be an issue.
To only print out the names that start with those letters you just need to index the first character c[0], e.g.:
phrase = input("Enter list of students")
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
Just be aware input() is generally considered unsafe because arbitrary code can be executed. A safer, but probably unnecessary at this level, approach would be:
import ast
phrase = ast.literal_eval(raw_input("Enter list of students"))
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
See my comment above, the phrase is a string when you input it. You have yet to make it into a list.
Try:
phrase = eval(input("Enter list of students")) #this evaluates the list put in
for names in phrase:
for letters in names:
if letters in 'abcdefghiABCDEFGHI':
print(names)
Next up
phrase = eval(input("Enter list of students"))
i = 0
while i < len(phrase): #for each item in phrase up to the end!
for letters in phrase[i]
if letters in 'abcdefghiABCDEFGHI':
print phrase[i]
phrase.pop(i)
i-=1 #set i backwards (as the incrementer downstairs will set it back to normal"
break #get out of this loop only one print please
i+=1 #fast way to increment

Categories