Spliting string without spaces - python

I am trying to find a way to split each letter in a word to a list.
I have tried to do this with a for letter in message add space but this hasn't worked.
message = 'hello'
for letter in message:
letter += ' '
message = message.split()
print(message)
I get
['hello']
I want
['h', 'e', 'l', 'l', 'o']

A string is an iterable. When iterating over a string, it yields each character individually. The list() constructor takes an iterable and creates a list out of its individual elements. So:
message = 'hello'
message = list(message)
print(message)
# ['h', 'e', 'l', 'l', 'o']

A string is already an array of charecters. Use list(str)
Example:
message = 'hello'
char_array = list(message)
print char_array

Related

How to use "None" in list when i'm using .index() and object wight not exist in list

I want to write a function that encrypt text using caesar cipher. But I want to let non-letters characters to be the same.
I have list with alphabet and a "questions for user"
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
This is function which should let non-letters to be in code non changed
def encrypt(text, shift):
text_encrypted = [] # blank text
for letter in text: # check every letter
indeksik = alphabet.index(letter)
if indeksik == None:
text_encrypted.append(letter)
else:
text_encrypted.append(alphabet[indeksik + shift])
But then I'm getting this error:
Tracebac k (most recent call last):
File "C:\Users\mateu\PycharmProjects\Cipher\main.py", line 25, in <module>
encrypt(text, shift)
File "C:\Users\mateu\PycharmProjects\Cipher\main.py", line 16, in encrypt
indeksik = alphabet.index(letter)
ValueError: ' ' is not in list
I know that ' ' is not in list. That's the point - how I can still append to another list these spaces and other non-alphabetical characters?
(Yes, I know that in this moment it will crash when I will shift letter "beyond z" - but I will work with this later)
index() raises a ValueError exception if the value is not in the list. You can do something like:
if letter in alphabet:
# Found the letter
else:
# Not found
The other possible solution is to handle the exception itself, but I'd probably go with the first one.
For
indeksik = alphabet.index(letter)
If letter is not found in alphabet, a ValueError exception is raised.
for letter in text: # check every letter
if letter in alphabet:
indeksik = alphabet.index(letter)
text_encrypted.append(alphabet[indeksik + shift])
else:
text_encrypted.append(letter)
If you use a string, preferably not typing (and possibly mistyping) it yourself, then you can use find and you'll get -1 instead of an error:
>>> from string import ascii_lowercase as alphabet
>>> alphabet.find('c')
2
>>> alphabet.find(' ')
-1

How do I replace a string at a index in python? [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 1 year ago.
So I already know how to remove a index like this:
i = "hello!"
i= i[:0] + i[1:]
print(i)
'ello!'
But how do I replace it?
So maybe I wanted to now put a H where the old h was but if I do this:
i[0] ="H"
I get this error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
i[0] ="H"
TypeError: 'str' object does not support item assignment
How do I fix this?
Strings are immutable in Python, so you can't assign like i[0] = 'H'. What you can do is convert the string to list, which is mutable, then you can assign new values at a certain index.
i = "hello!"
i_list = list(i)
i_list[0] = 'H'
i_new = ''.join(i_list)
print(i_new)
Hello!
Without creating a list you could also do:
i = "hello!"
i = "H" + i[1:]
More general:
def change_letter(string, letter, index): # note string is actually a bad name for a variable
return string[:index] + letter + string[index+1:]
s = "hello!"
s_new = change_letter(s, "H", 0)
print(s_new)
# should print "Hello!"
Also note there is a built in function .capitalize()
This is a duplicate of this post
As said there you have to make a list out of your string and change the char by selecting an item from that list and reassigning a new value and then in a loop rebuilding the string.
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
i = "hello!"
print(i) ## will print hello!
i = "H" + i[1:]
print(i) ## will print Hello!

Split user input string into a list with every character

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']

How to get all substrings in a list of characters (python)

I want to iterate over a list of characters
temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
so that I can obtain two strings, "hello" and "world"
My current way to do this is:
#temp is the name of the list
#temp2 is the starting index of the first alphabetical character found
for j in range(len(temp)):
if temp[j].isalpha() and temp[j-1] != '#':
temp2 = j
while (temp[temp2].isalpha() and temp2 < len(temp)-1:
temp2 += 1
print(temp[j:temp2+1])
j = temp2
The issue is that this prints out
['h', 'e', 'l', 'l', 'o']
['e', 'l', 'l', 'o']
['l', 'l', 'o']
['l', 'o']
['o']
etc. How can I print out only the full valid string?
Edit: I should have been more specific about what constitutes a "valid" string. A string is valid as long as all characters within it are either alphabetical or numerical. I didn't include the "isnumerical()" method within my check conditions because it isn't particularly relevant to the question.
If you want only hello and world and your words are always # seperated, you can easily do it by using join and split
>>> temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
>>> "".join(temp).split('#')
['hello', 'world']
Further more if you need to print the full valid string you need to
>>> t = "".join(temp).split('#')
>>> print(' '.join(t))
hello world
You can do it like this:
''.join(temp).split('#')
List has the method index which returns position of an element. You can use slicing to join the characters.
In [10]: temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
In [11]: pos = temp.index('#')
In [14]: ''.join(temp[:pos])
Out[14]: 'hello'
In [17]: ''.join(temp[pos+1:])
Out[17]: 'world'
An alternate, itertools-based solution:
>>> temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
>>> import itertools
>>> ["".join(str)
for isstr, str in itertools.groupby(temp, lambda c: c != '#')
if isstr]
['hello', 'world']
itertools.groupby is used to ... well ... group consecutive items depending if they are of not equal to #. The comprehension list will discard the sub-lists containing only # and join the non-# sub-lists.
The only advantage is that way, you don't have to build the full-string just to split it afterward. Probably only relevant if the string in really long.
If you just want alphas just use isalpha() replacing the # and any other non letters with a space and then split of you want a list of words:
print("".join(x if x.isalpha() else " " for x in temp).split())
If you want both words in a single string replace the # with a space and join using the conditional expression :
print("".join(x if x.isalpha() else " " for x in temp))
hello world
To do it using a loop like you own code just iterate over items and add to the output string is isalpha else add a space to the output:
out = ""
for s in temp:
if s.isalpha():
out += s
else:
out += " "
Using a loop to get a list of words:
words = []
out = ""
for s in temp:
if s.isalpha():
out += s
else:
words.append(out)
out = ""

Take user input and put it in a list of characters (Python 3)

I'm looking for a simple way of taking input from the user and placing it into a list of single character elements.
For example:
Input: word2
List = ['w', 'o', 'r', 'd', '2']
Use input to take input:
>>> word = input()
word2 <--- user type this.
>>> word
'word2'
Use list to conver a string into a list containg each character.
>>> list(word)
['w', 'o', 'r', 'd', '2']
This works because list accepts any iterable and string objects is iterable; Iterating a string yield each character.

Categories