Split user input string into a list with every character - python

I'm trying to write a program for the micro:bit which displays text as morse code. I've looked at multiple websites and Stack Overflow posts for a way to split a string into characters.
E.g.
string = "hello"
to
chars = ["h","e","l","l","o"]
I tried creating a function called array, to do this, but this didn't work.
I then tried this:
def getMessage():
file = open("file.txt", "r")
data = file.readlines()
file.close()
words = []
for line in data:
for word in line:
words.append(word)
return words
Any ideas?

You can use builtin list() function:
>>> list("A string")
['A', ' ', 's', 't', 'r', 'i', 'n', 'g']
In your case, you can call list(getMessage()) to convert the contents of the file to chars.

You can try something like this:
word="hello"
result = []
result[:0] = word
print(result)
Now result will be ['h', 'e', 'l', 'l', 'o']

Related

How do we remove ' ' from the list?

So I am trying to read line by line from the text file using python And I got list of lists. And I have to use the elements of the list to create dictionary. So what I did was
list1 = []
for line in file:
lines = line.strip().split()
list1.append(lines)
print(list1)
And what I got when I ran it is the list of lists but something different than what I wanted to get, I got something like this,
['a,b,c,d,e,f']
What I wanted to get was something like this,
[a,b,c,d,e,f]
So how do we get rid of that ' ' inside the list?
I tried to use remove method, but it did not work.
you just need to change the separator in the strip from the default white space to ",".
i.e you just need to add the separator argument in the strip function .
list1 = []
for line in file:
lines = line.strip().split(',')
list1.append(lines)
print(list1)
so if text is:
a,b,c,d,e,f
the strip function would take the separator as "," and create a list for it.
hence the output would be:
['a','b','c','d','e','f']
therefore finally you just need to change the separator argument of line.strip() from white spaces to comma separated list and you are done with it .
What you have here is a list with a single element. It contains a single string which is 'a,b,c,d,e,f'.
We can double-check:
data = ['a,b,c,d,e,f']
print(len(data)) # prints 1
print(data[0]) # prints 'a,b,c,d,e,f'
What you want is to split this string into a list:
row = data[0].split(',')
Now row contains what you expected data to be, which is ['a', 'b', 'c', 'd', 'e', 'f'].
In a real case you would probably fix this while reading the file, the code might look like this:
list1 = []
with open('test.csv') as test_file:
for line in test_file:
list1.append(line.strip().split(','))
print(list1)
Now you would then have a list per line in your input file:
[
['a', 'b', 'c', 'd', 'e', 'f'],
['g', 'h', 'i', 'j', 'k', 'l'],
]
Just change the delimeter from '' to ','
list1 = []
for line in file:
lines = line.strip().split(,)
list1.append(lines)
print(list1)
you are good to go

Remove \n character in a list without breaking apart every letter

I am trying to remove '\n' from the end of each element in a list imported from a .txt file
Here is the file I am importing:
NameOfFriends.txt
Joeseph
Mary
Alex
Here is the code I am running
a = open('NameOfFriends.txt', 'r').readlines()
print(a)
newList = str(a)
print(type(newList[0]))
for task in newList:
newList = [task.replace('\n', '') for task in newList]
print(newList)
Here is the output:
['Joeseph\n', 'Mary\n', 'Alex']
<class 'str'>
['[', "'", 'J', 'o', 'e', 's', 'e', 'p', 'h', '\\', 'n', "'", ',', ' ', "'", 'M', 'a', 'r', 'y', '\\', 'n', "'", ',', ' ', "'", 'A', 'l', 'e', 'x', "'", ']']
Here is the desired output when variable newList is printed:
['Joeseph', 'Mary', 'Alex']
with open('NameOfFriends.txt') as file:
names = []
for name in file.readlines():
names.append(name.strip("\n"))
print(names)
You don't need an extra for loop, just do:
newList = [task.replace('\n', '') for task in newList]
Or don't even add these codes, just do on the first line:
a = list(open('NameOfFriends.txt', 'r'))
newList isn't a list, it's a string because you did:
newList = str(a)
There's no need to do that.
You can remove the newlines when you're reading the file:
a = [line.rstrip('\n') for line in open('NameOfFriends.txt', 'r').readlines()]
You don't need a loop or comprehension to do it , if you want to remove only the line breaks from the text. You can use the splitlines function for that.
a = open('NameOfFriends.txt', 'r').read().splitlines()
This will do what you need.
You can use strip() or replace() for this
replace()
a = open('NameOfFriends.txt', 'r').readlines()
new_list = []
for task in a:
new_list.append(task.replace('\n', ''))
print(new_list)
strip()
a = open('NameOfFriends.txt', 'r').readlines()
new_list = []
for task in a:
new_list.append(task.strip('\n'))
print(new_list)
with open('NameOfFriends.txt', 'r') as friends:
#With allows file to close automatically when code block is done.
friends = friends.read() #converts friends to string
friends_separated = friends.split() #converts string to list
print(friends_separated) #prints

How to add 100 words to a list using while loop?

i want to add a word for ex. 100 times to a list, here is my code
my expected result is ['word', 'word', 'word'...]
i = 1
text = [ ]
while i <= 100:
text += 'word'
i += 1
print(text)
the output is -> 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', ...
all the letters are added separately,
Can smbdy explain why? And what is the right code for adding 100 words to a list ?
Thank you
You want to use text.append(word) or text += ['word'] instead. When adding items to a list, += is effectively the same as .extend.
Since strings can be iterated on, it's adding each character into the list individually
Use extend.
text = ['existing', 'words']
text.extend(['word']*100)
print(text)
mul=100
text = ['existing', 'words']
# repeat the text n-times
m_text=[[x]*mul for x in text]
# flattened list
flat_list = [item for sublist in m_text for item in sublist]

Python - how to split a file object up into a list of individual characters?

I'm importing data from a file object. It's pretty simple; it's a .txt file, and the data was entered like this: ABCDEFGHIJKLMNOPQRSTUVWXYZ
I am trying to get it to be a list of individual characters, e.g.
my_list = ['A', 'B', 'C', 'D', ...etc.]
but it's showing up like this:
my_list = ['ABCDEFGHIBJK... etc.]
Where am I going wrong?
def split(string):
return [char for char in string]
# This opens a file, gets a file object, and returns it to the program.
def get_file_object1():
infile = open(r'#', 'r')
file_object = infile.readlines()
testing = split(file_object) # this is a test line
print(testing) # this is a test line
print(split('This is another test.'))
infile.close()
return file_object
Note: when I pass the file object to split(file_object), I get this
['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
But when I pass a string of text to split('This is another string.'), I get this:
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', 'o', 't', 'h', 'e', 'r', ' ',
't', 'e', 's', 't', '.']
Simple, just read and apply list() ;-)
with open(r'C:\Users\Liz\Desktop\PYTHON PROBLEMS\cipherUpper.txt') as f:
myList = list(f.read().strip())
Get myList as your list
The return type of readlines() is list, so you're basically doing this:
string = ['ABC..', ...]
[char for char in string]
where char is equal to 'ABC..'
so you need to iterate over the result of readlines:
testing = []
for line in f.readlines():
testing = testing + split(line)
or read a single line with readline() instead.
split is iterating the object it receives
When you pass file_object, the lines of the file are iterated. There is only one line so you receive the first line as a string.
testing = split(file_object) # >> ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
When you pass a string, the characters of the string are iterated so you get a list of characters.
print(split('This is another test.')) # >> ['T', 'h', 'i', 's', ....

How to iterate through characters and lines in Python?

Let's say I have a file containing this:
xxoxoxoxox
xxxxxxxxxx
xoxoxoxoxo
ooxoxoxoxo
and I want to iterate through each character and line and store them.
I know that if the characters are separated by spaces, I can do this:
mylist=[]
with open("myfile.txt") as myfile:
for line in file:
line = line.strip().split(" ")
first = line[0]
second = line[1]
alist = [first, second]
mylist.append(alist)
But how do I do something like this without spaces as delimiters? I tried .split()
and
for line in file:
for char in line:
But neither seems to work.
Thanks in advance for any help!
Here is a small snippet that might be useful to you.
Say you have a file called 'doc.txt' with two lines:
kisskiss
bangbang
With the following python script:
with open('doc.txt', 'r') as f:
all_lines = []
# loop through all lines using f.readlines() method
for line in f.readlines():
new_line = []
# this is how you would loop through each alphabet
for chars in line:
new_line.append(chars)
all_lines.append(new_line)
The output is:
>>> all_lines
Out[94]:
[['k', 'i', 's', 's', 'k', 'i', 's', 's', '\n'],
['b', 'a', 'n', 'g', 'b', 'a', 'n', 'g', '\n']]
More "pythonic" way:
def t():
r = []
with open("./test_in.txt") as f_in:
[r.extend(list(l)) for l in f_in]
return r
Note that you can't use return [r.extend(list(l)) for l in f_in] because extend returns None.

Categories