How to split a word into letters in Python - python

I was wondering if there is a straightforward way to do the following:
Input string:
input = 'Hello'
Output string:
output = 'H,e,l,l,o'
I understand you can do list(input), but that returns a list and I wanted to get the string rather than the list.
Any suggestions?

In [1]: ','.join('Hello')
Out[1]: 'H,e,l,l,o'
This makes use of the fact that strings are iterable and yield the individual characters when iterated over.

outputstr = ','.join(inputstr)

Since NPE already provided the ','.join('Hello') method, I have a different solution (though it may not be more Pythonic):
inputStr, outputStr = 'hello', ''
for char in inputStr: outputStr += char + ','
print outputStr[:-1]
Output: 'h,e,l,l,o'.

Related

compare list elment to a string

I have the following list
l=['web','python']
and the following string
st='python, C, something, find'
I want to check if any element in the list is in the string
I tried using
any(x in l for x in st)
however it gives false
seems python can't recognize the element in the string, is there a way to check elements from list to a string if there is a match. i did it successfully using a for a loop and splitting the string to a list however that is not efficient with the real data as it contain a long lists and strings. need something efficient.
thanks
You would first need to split the string, or else you will be iterating over the individual characters.
Try this:
l=['web','python']
st='python, C, something, find'
any([x in l for x in st.split(',')]) # True
But this isn't the most efficient. For better performance, you could take a look into using a trie.
If your would like to check if any element in the list is in the string
then your code should be
any(x in st for x in l)
You can use this method
word_list = ['web','python']
string = 'python, C, something, find'
exist = filter(lambda x : x in string , word_list)
print(list(exist))
output:
['python']
You were close. How about:
any(x in l for x in st.replace(',', '').split())
which returns:
True
A different approach:
import re
re.search(r'\b(' + '|'.join(l) + r')\b', st)
The search will return None if there's no match and the match if there is one. You can use it like:
if re.search(r'\b(' + '|'.join(l) + r')\b', st):
print(f'there was a match: {t.groups()}')
else:
print('no match')

Alphabet position in python

Newbie here...Trying to write a function that takes a string and replaces all the characters with their respective dictionary values.
Here is what I have:
def alphabet_position(text):
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8':'i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
text = text.lower()
for i in text:
if i in dict:
new_text = text.replace(i, dict[i])
print (new_text)
But when I run:
alphabet_position("The sunset sets at twelve o' clock.")
I get:
the sunset sets at twelve o' cloc11.
meaning it only changes the last character in the string. Any ideas? Any input is greatly appreciated.
Following your logic you need to create a new_text string and then iteratively replace its letters. With your code, you are only replacing one letter at a time, then start from scratch with your original string:
def alphabet_position(text):
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
new_text = text.lower()
for i in new_text:
if i in dict:
new_text = new_text.replace(i, dict[i])
print (new_text)
And as suggested by Kevin, you can optimize a bit using set. (adding his comment here since he deleted it: for i in set(new_text):) Note that this might be beneficial only for large inputs though...
As your question is generally asking about "Alphabet position in python", I thought I could complement the already accepted answer with a different approach. You can take advantage of Python's string lib, char to int conversion and list comprehension to do the following:
import string
def alphabet_position(text):
alphabet = string.ascii_lowercase
return ''.join([str(ord(char)-96) if char in alphabet else char for char in text])
Your approach is not very efficient. You are recreating the string for every character.
There are 5 e characters in your string. This means replace is called 5 times, even though it only actually needs to do anything the first time.
There is another approach that might be more efficient. We cant use str.translate unfortunately, as it's remit is one to one replacements.
We just iterate the input and produce a new string character by character.
def alphabet_position2(text):
d = {L: str(i) for i, L in enumerate('abcdefghijklmnopqrstuvwxyz', 1)}
result = ''
for t in text.lower():
result += d.get(t, t)
return result
This is a pretty simple approach with list comprehension.
Generate k:v in this format from string module, 1:b instead of b:1
import string
def alphabet_position(text):
alphabeths = {v: k for k, v in enumerate(string.ascii_lowercase, start=1)}
return " ".join(str(alphabeths.get(char)) for char in text.lower() if char in alphabeths.keys())

python anti_vowel function error

Hi I'm doing the anti_vowel function, which basically takes out all of the vowels from the input. I'm confused about this code. Why doesn't it work? (For the last word "word") The output for "Hey look words!" is:
Hy lk words!
If anyone can help, thank you so so much!
def anti_vowel(text):
l = []
s = ""
for i in text:
l.append(i)
for i in l:
if i in "aeiouAEIOU":
x = l.index(i)
l.pop(x)
print l
print "".join(l)
anti_vowel("Hey look words!")
The output is:
Hy lk Wrds!
Modifying an iterator (your list) while looping over it will end up yielding very unexpected results, and should always be avoided. In your particular case, as you delete your list, you are actually reducing it, and therefore actually ending it "earlier" than you should.
What you should be doing instead is collecting your data in a new list based on what you are trying to filter. So, instead of popping, instead you should check for non-vowels and append to a new list. Taking your exact code and changing just that logic, you should be good:
def anti_vowel(text):
l = []
s = ""
for i in text:
l.append(i)
new_l = []
for i in l:
if i not in "aeiouAEIOU":
new_l.append(i)
print("".join(new_l))
So, running that code now, will yield the following output:
Hy lk wrds!
Now, to go over some areas in your code where you are doing some unnecessary steps that you can simplify. You do not need to loop through your string like that and create a new list at the beginning of your function. Your string can already be iterated over, so simply do exactly that using your string. In other words you do not need this:
l = []
s = ""
for i in text:
l.append(i)
So, instead, you can just start from:
new_l = []
for i in text:
if i not in "aeiouAEIOU":
new_l.append(i)
print("".join(new_l))
So, the above code now simply iterates over your string text, character-by-character, and we will check to make sure that each character does not match the vowels, and append it to our new list.
Finally, for the sake of really making this short. We can throw this in to a pretty little line making an expression that we can then call join on to create our string. Also! you don't need to check all cases since you can just keep your characters to a single casing by calling the lower method on your string you are iterating through to keep all under a single case, to make it simpler to check:
def anti_vowel(text):
return ''.join(c for c in text if c.lower() not in "aeiou")
print(anti_vowel("Hey look words!"))
You're deleting elements from the list as you iterate over it. You're actually shortening the list before the loop can even reach the '...words' part.
A couple of other things. If you want to convert a string to a list, you can just do:
myList = list(myString)
Next, when iterating, do iterate over a copy of the list.
for i in l[:]:
The [:] operator creates a spliced copy, and iterates over that. This is the big fix, and it'll get your code running as expected. For that particular input, you get Hy lk wrds!.
Simpler alternative? Don't even use a list. You can work with strings, using the str.replace function:
def anti_vowel(text):
newText = text[:]
for i in 'aeiouAEIOU':
newText = newText.replace(i, '')
print(newText)
return newText
newText = anti_vowel("Hey look words!")
print(newText)
Output:
Hy lk wrds!
An even simpler version? You can use str.translate:
>>> x = {c : '' for c in 'aeiouAEIOU'}
>>> "Hey look words!".translate(str.maketrans(x))
'Hy lk wrds!'
def anti_vowel(text):
new = ''
for char in text:
if char in "aeiou" or char in "AEIOU":
ala = text.replace(char, '')
try doing this. Hope it helps
You should never alter an iterable (list in this case) while you're iterating over it. Bad things can and do happen.
Here's a different and a bit simpler way to do it. Instead of removing vowels from a list, instead, we create an empty list, and put the constants into it:
def anti_vowel(text):
consts = []
for letter in text:
if letter not in "aeiouAEIOU":
consts.append(letter)
print "".join(consts)
anti_vowel("Hey look words!")
Output:
Hy lk wrds!
Since other answers have already provided you with an explanation of your problem, and showed how to fix your code, I'll show you how you can make your function much smaller and cleaner.
You can use a generator comprehension to filter out all of the vowels from your input, and use ''.join() to join each individual character back together:
>>> def anti_vowels(text):
return ''.join(c for c in text if c.lower() not in 'aeiou')
>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hello, World!')
'Hll, Wrld!'
>>> anti_vowels('I love vowels!')
' lv vwls!'
>>> anti_vowels('Ronald Regan')
'Rnld Rgn'
>>> anti_vowels('Carts And BOxes')
'Crts nd Bxs'
>>>
The important part of the comprehension is the the if part. It will only add the current character to the generator if it is not a vowel. I've also eliminated the extra uppercase vowels by using c.lower(). This force c to become lower case, so we can treat the character as if it were case insensitive.
You can also easily extend this to allow the user to specify the vowels they want to filter out (such as y):
>>> def anti_vowels(text, vowels='aeiou'):
return ''.join(c for c in text if c.lower() not in vowels)
>>> anti_vowels('Hey look words!')
'Hy lk wrds!'
>>> anti_vowels('Hey look words!', vowels='aeiouy')
'H lk wrds!'
>>>

In python, how can I use regex to replace square bracket with parentheses

I have a list :list = [1,2,3]. And I would like to convert that into a string with parentheses: string = (1,2,3).
Currently I am using string replace string = str(list).replace('[','(').replace(']',')'). But I think there is a better way using regex.sub. But I have no idea how to do it. Thanks a lot
If you do indeed have a list, then:
>>> s = [1,2,3]
>>> str(tuple(s))
'(1, 2, 3)'
You could use string.maketrans instead -- I'm betting it runs faster than a sequence of str.replace and it scales better to more single character replacements.
>>> import string
>>> table = string.maketrans('[]','()')
>>> s = "[1, 2, 3, 4]"
>>> s.translate(table)
'(1, 2, 3, 4)'
You can even use this to remove characters from the original string by passing an optional second argument to str.translate:
>>> s = str(['1','2'])
>>> s
"['1', '2']"
>>> s.translate(table,"'")
'(1, 2)'
In python3.x, the string module is gone and you gain access to maketrans via the str builtin:
table = str.maketrans('[]','()')
There are a billion ways to do this, as demonstrated by all the answers. Here's another one:
my_list = [1,2,3]
my_str = "(%s)" % str(my_list).strip('[]')
or make it recyclable:
list_in_parens = lambda l: "(%s)" % str(l).strip('[]')
my_str = list_in_parens(my_list)
str([1,2,3]).replace('[','(').replace(']',')')
Should work for you well, and it is forward and backward compatible as far as I know.
as far as re-usability, you can use the following function for multiple different types of strings to change what they start and end with:
def change(str_obj,start,end):
if isinstance(str_obj,str) and isinstance(start,str) and isinstance(end,str):
pass
else:
raise Exception("Error, expecting a 'str' objects, got %s." % ",".join(str(type(x)) for x in [str_obj,start,end]))
if len(str_obj)>=2:
temp=list(str_obj)
temp[0]=start
temp[len(str_obj)-1]=end
return "".join(temp)
else:
raise Exception("Error, string size must be greater than or equal to 2. Got a length of: %s" % len(str_obj))
All you need is:
"(" + strng.strip('[]') + ")"
It works for both single element and multi-element lists.
>>> lst = [1,2,3]
>>> strng = str(lst)
>>> "(" + strng.strip('[]') + ")"
'(1, 2, 3)'
>>> lst = [1]
>>> strng = str(lst)
>>> "(" + strng.strip('[]') + ")"
'(1)'
If you really want to use regex I guess this would work. But the other posted solutions are probably more efficient and/or easy to use.
import re
string = str(list)
re.sub(r"[\[]", "(", string)
re.sub(r"[\]]", ")", string)
#mgilson something like this you mean?
def replace_stuff(string):
string_list = list(string)
pattern = re.compile(r"[\[\]]")
result = re.match(pattern, string)
for i in range(len(result.groups())):
bracket = result.group(i)
index = bracket.start()
print(index)
if bracket == "[":
string_list[index] = "("
else:
string_list[index] = ")"
return str(string_list)
It doesn't quite work, for some reason len(result.groups()) is always 0 even though the regex should find matches. So couldn't test whether this is faster but because I couldn't get it to work I couldn't test it. I have to leave for bed now so if someone can fix this go ahead.
Try this:
'({0})'.format(', '.join(str(x) for x in list))
By the way, it's not a good idea to name your own variables list since it clashes with the built-in function. Also string can conflict with the module of the same name.

How do I replace a character in a string with another character in Python?

I want to replace every character that isn't "i" in the string "aeiou" with a "!"
I wrote:
def changeWord(word):
for letter in word:
if letter != "i":
word.replace(letter,"!")
return word
This just returns the original. How can I return "!!i!!"?
Strings in Python are immutable, so you cannot change them in place. Check out the documentation of str.replace:
Return a copy of the string with all occurrences of substring old replaced by new. If the
optional argument count is given, only the first count occurrences are replaced.
So to make it work, do this:
def changeWord(word):
for letter in word:
if letter != "i":
word = word.replace(letter,"!")
return word
Regular expressions are pretty powerful for this kind of thing. This replaces any character that isn't an "i" with "!"
import re
str = "aieou"
print re.sub('[^i]', '!', str)
returns:
!!i!!
something like this using split() and join():
In [4]: strs="aeiou"
In [5]: "i".join("!"*len(x) for x in strs.split("i"))
Out[5]: '!!i!!'
Try this, as a one-liner:
def changeWord(word):
return ''.join(c if c == 'i' else '!' for c in word)
The answer can be concisely expressed using a generator, there's no need to use regular expressions or loops in this case.
Nobody seems to give any love to str.translate:
In [25]: chars = "!"*105 + 'i' + "!"*150
In [26]: 'aeiou'.translate(chars)
Out[26]: '!!i!!'
Hope this helps
Generally in python string are immutable that means it can't be changed
after its creation. So we have to convert string into mutable and that can be possible using list as it is mutable.
string="Love"
editable = list(string)
editable[2]='s'
string=''.join(editable)
output:Lose

Categories

Resources