Function it gives me position of letter in string (python) - python

I mean like it is gonna ask me to type some string and ask me to type one letter and gives me position of it.
like "Hello"
i wanna letter e
it gives me position 2.
Thank you for answer

There are two ways I know of that you could use, one makes the string into a list, making it easier to iterate through, and the other just iterates through the string.
Option #1 (String):
string = 'Hello'
for char in string:
if char == 'e':
break <or whatever code you want here>
Option #2 (List):
def split(string):
return [char for char in string]
string = 'Hello'
for char in split(string):
if char == 'e':
break <or your code>

You can use the .find method.
string = input() # Gets the input from the user
character = input() # Gets another input from the user (the character)
index = string.find(character) # This function is going to return the index of character in string
print(index + 1)
It prints index + 1 because the index in python (actually most languages) starts at 0
Input:
Hello
e
Output:
2

Related

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

How would I execute this? Python

I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])

String replace printing too many instances of character 'e'

I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
eg: apple becomes aaaappleeee
It works for every vowel, except for e, in which it repeats e an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to i+i+i+i, i*4, i(4), (i+i)*2, but nothing seems to help.
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
exclamation('excellent') should return eeeexceeeelleeeent!
however, it returns:
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!
As stated, the function works fine for all other vowels, except e.
Thank you!
You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'
For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. Never modify the iterable you’re iterating over.
It's not that e is being treated differently, but rather that you're replacing each e with eeee for as many es as there are in the word. If you try other words with multiples of the same vowel, you would see the same behavior there.
Instead of replacing for each vowel in the string, you should be doing each replacement once, which will effect every instance of that vowel in the string:
def exclamation(s):
for vowel in 'aeiou':
s = s.replace(vowel, vowel*4)
return s + '!'
print(exclamation('excellent'))
# 'eeeexceeeelleeeent!'
Note that this only works if the word is already lowercase (though that would be easy to fix, add capital vowels to the loop).
Another way of doing this would be to define a translation table to do all of the replacements at once:
trans = str.maketrans({vowel: vowel*4 for vowel in 'aeiou'})
def exclamation(s):
return s.translate(trans)
def exclamation(string):
result = ''
for i in string:
if i in 'aeiou':
vowel = i * 4
else:
vowel = i
result += vowel
return result + '!'
The reason why replace didnt work for excellent is because we have 3 'e' in which means for each of the 'e' in the loop, replace will multiply by 4 which will definitely give you 12 'e's per one 'e' in excellent
It is happening because your loop will consider the replaced 'e's as the element of the string as well.
Here is what I am saying:
String is excellent
Iterate through the string and check if the letter is vowel
If the letter is vowel, write that vowel 4 times.
By following the above steps, we will find this result as the first iteration.
First iteration will work on the first letter which is 'e' and will replace it with 'eeee'. So at the end of the first iteration, our final string will be: 'eeeexcellent'
Now for the second iteration, it will consider the final string we got after the first iteration. And for second iteration, the word to be consider will be 'e' only. So as you can see, you need to maintain the string as it is after each iteration, and save the replaced result to a new string. (it will always be a new string after all as string is not mutable)
def exclamation(string):
tmp = '' #taking temporary variable to store the current data
for i in string:
if i in 'aeiou':
tmp += i*4 # i*4 only if i is vowel
else:
tmp += i # keeping i as it is if it's not vowel
return tmp + '!'
You can also try list list comprehension which is easy to read and understand as well:
def exclamation(string):
newstr = [ i*4 if i in 'aeiou' else i for i in string]
return ''.join(newstr)+'!'

Python empty string index error

How do I stop the index error that occurs whenever I input an empty string?
s = input("Enter a phrase: ")
if s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
print("an", s)
else:
print("a", s)
You can use the str.startswith() method to test if a string starts with a specific character; the method takes either a single string, or a tuple of strings:
if s.lower().startswith(tuple('aeiou')):
The str.startswith() method doesn't care if s is empty:
>>> s = ''
>>> s.startswith('a')
False
By using str.lower() you can save yourself from having to type out all vowels in both lower and upper case; you can just store vowels into a separate variable to reuse the same tuple everywhere you need it:
vowels = tuple('aeiou')
if s.lower().startswith(vowels):
In that case I'd just include the uppercase characters; you only need to type it out once, after all:
vowels = tuple('aeiouAEIOU')
if s.startswith(vowels):
This will check the boolean value of s first, and only if it's True it will try to get the first character. Since a empty string is boolean False it will never go there unless you have at least a one-character string.
if s and s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
print("an", s)
General solution using try/except:
s = input("Enter a phrase: ")
try:
if s[0].lower() in "aeiou":
print("an", s)
else:
print("a", s)
except IndexError:
# stuff you want to do if string is empty
Another approach:
s = ""
while len(s) == 0:
s = input("Enter a phrase: ")
if s[0].lower() in "aeiou":
print("an", s)
else:
print("a", s)
Even shorter:if s[0:][0] in vowels: but of course this not pass as 'pythonic' I guess. What it does: a slice (variable[from:to]) may be empty without causing an error. We just have to make sure that only the first element is returned in case the input is longer than 1 character.
Edit: no, sorry, this will not work if s=''. You have to use 'if s[0:][0:] in vowels:' but this clearly crosses a line now. Ugly.
Just use
if s:
if s[0] in vowels:
as suggested before.

Counting letters in a string

I am wondering how to count specific letters in a string. The first thing that popped into my head was the function len. Out of curiosity, is there a way to write this code without using built in functions and using len?
There is a question asked similar to this here and I am having trouble understanding it.
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count = count + 1
return count
What exactly is going on in if char == c: and count += 1? I understand why the person started with a for loop but I don't understand why place an if after?
The if is needed because you only want to count instances of a specific character, char. Without it, you would wind up doing count = count + 1 for every character in the string, so you'd get the full string length, not the amount of specific character you're looking for.
With comments in code:
for c in word: # go through each character in code
if char == c: # if the character is the one we're counting
count = count + 1 # add one to the current count of characters
Strings have a built in count() method:
>>> s = 'aaabbbccc'
>>> s.count('a')
3
>>> s.count('aa')
1
Have you tried the Python Wiki?
It states that ANY object with an iterating function can be cycled through, which answers your second question.
Since you don't want to use the len function, you can use the for loop like in the answer you linked to cycle through the object (the String word) looking for the character char, recording each time the char is found with count.
The parameter char needs to be found in word parameter, and so c is just a variable to set to each letter (or character, not all parts of the String may be an alphabetical letter) as it cycles through word.
The reason for the if statement is so when the cycling variable c equals char, the block can be executed. In this particular block, the count is being iterated up (count = count + 1), and once the function is done with iterating through the for loop, it will return count (how many times char was found, effectively counting specific letters in the String as you asked for).
Long-winded but in short, yes, that function you posted will give you a count of how many times the letter is in the word.
You want to count only for specific char. Meaning that if you have the word "hello" and the letter "l", you want to return 2 because "l" appears 2 times in "hello".
The if simply checks if the char is the char you want, if that's the case, you increment the counter by one - for c in word: iterates on the chars of word.
Python's syntax is very readable and easy to understand, try to speak the code and you'll understand what it does.
Another way to do that is:
print len([c for c in word if c == char])
Example:
[c for c in 'hello world' if c == 'l']
Will return:
['l', 'l', 'l']
Then len will return 3.
Using collections.Counter
>>> word = "Hallelujahhhhh"
>>> from collections import Counter
>>> Counter(word)
Counter({'h': 5, 'l': 3, 'a': 2, 'e': 1, 'H': 1, 'j': 1, 'u': 1})
for c in word:
In this statement word will be taken as a list of a string, c is each character from that list. That means loop will repeat for each character of the word.
So in this statement if char == c: for every character of word will be compare with char.
If the statement is true then count will increase by 1.
So, As per your question
if char == c: compare char with each character of word
and
count+=1 will increase the value of count by 1

Categories