How to double a char in a string? - python-2.7

I am trying to write a function that takes two arguments, a string and a letter. The function should then double the number of letter in the string. For example:
double_letters("Happy", "p")
Happppy
what i have done so far;
def double_letter(strng, letter):
new_word = ""
for char in strng:
if char == letter:
pos = strng.index(char)
new_word = letter+strng[pos:]
But this is giving me the output: pppy
how can i change the function to get the output: Happppy?

Use string.replace
string = 'happy'
letter = 'p'
string = string.replace(letter, letter + letter)
print string

You could use join and iterate through the characters in your string:
def double_letters(word, letter):
return "".join(2*i if i == letter else i for i in word)

Related

letter changer lowercase to uppercase(vice versa) : Whats wrong in my code?

I wanted to enter a word with upperandlower letter combination letters and then when i press enter it will change vice versa
def changer(word):
for letter in word:
if letter.isupper():
letter.lower()
elif letter.islower():
letter.upper()
print word
word = raw_input()
changer(word)
You must append the converted letters to new string, and returning the new string could be helpful, too.
def changer(word):
newWord = ""
for letter in word:
if letter.isupper():
newWord += letter.lower()
elif letter.islower():
newWord += letter.upper()
print newWord
return newWord
...you do not return anything. and strings in python are immutable; you can not change them in-place.
this is something you could try:
def swapcase(word):
return ''.join(c.lower() if c.isupper() else c.upper() for c in word)
print(swapcase(word='Hello')) # hELLO
where i use str.join to join the generator that iterates over the characters with the swapped case.
speed-wise str.translate may be the better choice:
from string import ascii_lowercase, ascii_uppercase
trans_table = str.maketrans(ascii_lowercase + ascii_uppercase,
ascii_uppercase + ascii_lowercase)
def swapcase(word):
return word.translate(trans_table)
print('Hello'.translate(trans_table)) # hELLO

Convert results in python to dictionary

help to convert a python code results, where its finding the number of time the vowel appears in a string to dictionary?
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
if char in vowels:
count += 1
print ('Number of vowels: ' + str(count))
The result should be:
for apple: {'a' : 1, 'e' : 1}
A simple change like this would do: instead of incrementing count += 1, increment directly on a dictionary:
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
vowels_dict = {}
for char in s:
if char in vowels:
if char in vowels_dict:
vowels_dict[char] +=1
else:
vowels_dict[char] = 1
print (vowels_dict)
First, let's make vowels into a dictionary . We will need a second one to hold on to the matches we make in the first loop:
s = "apples"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
We will need to modify your for loop slightly to increment the value of the corresponding key (the vowels):
for char in s:
if char in vowels:
vowels[char] += 1
The for loop above checks if char is a vowel (or put simply, is one of the keys found in vowels). If it is, we increment the corresponding key's value by 1. For example, if char was "a", the if statement would return True and the key ("a")'s value (the integer after the colon) will increase by one. Now all we need is to put all the keys whose value is over 0 into the matches dictionary:
for vowel in vowels:
if vowels[vowel] < 1: # The vowel didn't appear in the word
continue
else:
matches[str(vowel)] = vowels[vowel]
The last line creates a new key for the matches dictionary (the matches[str(vowel)] part) then assigns the value of the new key equal to the value of the respective key in the vowels dictionary (the = vowels[vowel] part). Now all we need to do is to print out the matches dictionary:
print matches
Full code:
count = 0
s = "apple"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
for char in s:
if char in vowels:
vowels[char] += 1
for vowel in vowels:
if vowels[vowel] < 1:
continue
else:
matches[str(vowel)] = vowels[vowel]
print matches

How to get non-alphabetical separator char from string

I have a situation where I want to get separator char from the given string like as below :-
String str1 = "saurabh|om|anurag|abhishek|jitendra"
String str2 = "amit,ankur,sumit,aniket,suheel"
String str3 = "aj-kumar-manav-lalit-gaurav"
-------
In above strings I want to get separator char as :-
String separatorStr1 = "|"
String separatorStr2 = ","
String separatorStr3 = "-"
Note :- separator char always will be non-alphabetical in string
Is there any way to achieve this.
Using groovy regexp and find ([^\w] is any non-alphanumeric character)
def getSeparator = { str ->
str.find(~/[^\w]/)
}
String str1 = "saurabh|om|anurag|abhishek|jitendra"
String str2 = "amit,ankur,sumit,aniket,suheel"
String str3 = "aj-kumar-manav-lalit-gaurav"
assert getSeparator(str1) == '|'
assert getSeparator(str2) == ','
assert getSeparator(str3) == '-'
Why is a - separator of str3? It could be a as well.
Assuming separator must be non-alphabetical loop through characters and look for first non-alphabetical character.
In future questions try to avoid other users guessing what you mean - try to define the subject of a topic.
By xenteros suggestion I have achieved this by following way :-
String str1 = "saurabh|om|anurag|abhishek|jitendra"
String str2 = "amit,ankur,sumit,aniket,suheel"
String str3 = "aj-kumar-manav-lalit-gaurav"
String separatorStr1 = str1.toCharArray().find { !Character.isLetterOrDigit(it) }
String separatorStr2 = str2.toCharArray().find { !Character.isLetterOrDigit(it) }
String separatorStr3 = str3.toCharArray().find { !Character.isLetterOrDigit(it) }
assert separatorStr1 == '|'
assert separatorStr2 == ','
assert separatorStr3 == '-'

Converting python string to pig latin

def isAlpha(c):
return (ord(c) >= 65 and ord(c) <= 95) or \
(ord(c) >= 97 and ord(c) <= 122)
# testing first function
print isAlpha("D")
print isAlpha("z")
print isAlpha("!")
s = "AEIOUaeiou"
def isVowel(c):
return s.find(c) > -1
# testing second function
print isVowel("A")
print isVowel("B")
print isVowel("c")
print isVowel(" ")
print isVowel("a")
def convPigLatin_word(word):
if isVowel(word[0]):
word += "way"
while not isVowel(word[0]):
word = word[1:] + word[0]
if isVowel(word[0]):
word += "ay"
return word
# testing third function
print convPigLatin_word("This")
print convPigLatin_word("ayyyyyylmao")
def translate(phrase):
final = ""
while phrase.find(" ") != -1:
n = phrase.find(" ")
final += convPigLatin_word(phrase[0:n]) + " "
phrase = phrase[n+1:]
if phrase.find(" ") == -1:
final += convPigLatin_word(phrase)
return final
print translate("Hello, this is team Number Juan") #Should be "elloHay, isthay isway eamtay umberNay uanJay"
I tried to create a code that transform a string into pig latin. But I got stuck on the non-alphanumeric character. The while loop only works up to the comma. How can I resolve that? I don't know where to implement the isAlpha code to check for non alphanumeric character. Any advice is helpful.
You can iterate through the words of a phrase by using .split(' '). Then you can test them for special characters using .isalpha()
pigLatin = lambda word: word[1:]+ word[0]+"ay"
def testChars(word):
text = ""
for char in list(word):
if char.isalpha():
text += char
else:
return pigLatin(text)+ char
def testWords(lis):
words = []
lis = lis.split(' ')
for word in lis:
if not word.isalpha():
words.append( testChars(word) )
else:
words.append(pigLatin(word))
return (' ').join(words)
phrase = "I, have, lots of! special> characters;"
print testWords(phrase)

Checking charcters in a string and outputing a Single message

a_lst = ['chair','gum','food','pizza']
letter = 'x'
for word in a_lst:
if letter not in word:
print ('no',letter)
elif letter in word:
print ('yes',letter)
Output:
no x
no x
no x
no x
Is there a way i can iterate though each item in "a_lst", check if each item has letter 'x'. if no item has letter 'x' print 'no x' just Once. If a word contains letter 'x', print 'yes x' just Once.
I think my logic is flawed somewhere.
Any suggestions?
Thanks
You could do this:
letter = 'x'
result = [a for a in a_lst if letter in a]
if result:
print('yes', letter)
else:
print('no', letter)
Explanation:
result will be [] if none of the words in a_lst has the letter. When you do a if result on an empty list, it returns False, otherwise it returns True. The conditional statements check and print the output statement accordingly.
Another way to do it in python is to use the filter function:
if filter(lambda x: letter in x, a_lst):
print('yes', letter)
else:
print('no', letter)
Yet another way to do it is to use any:
if any(letter in word for word in a_list):
print('yes', letter)
else:
print('no', letter)
any(letter in word for word in a_list) returns True if any of the words have the letter.
You can use the any function!
if any(letter in word for word in a_lst):
print('yes', letter)
else:
print('no', letter)
Have you tried something like this:
a = ['chair', 'gum', 'food', 'pizza']
letter = 'a'
result = 'no ' + letter
k = 0
for i in a:
if letter in a[k]:
print(a[k])
result = 'yes ' + letter
k += 1
print(result)