function to get nth letter from a string outputs number 1 - python

when I try to get second character of string "hello" to get letter e it prints "1" for some reason
string = "hello"
print_string = string[2]
print(print_string)
I want to get the letter e or nth letter but I just get number 1

It's not printing a number 1; it is printing a lowercase letter "L", which is the third letter in the world "hello". Remember that Python is zero-indexed, so the first letter will be at index 0, and the second letter at index 1. Try:
string = "hello"
print_string = string[1]
print(print_string)

python is index-based, counting begins with zero:
string = "hello"
h e l l o\
0 1 2 3 4
use:
print(string[0])
to access "h"
or:
print(string[4])
to access "o"
it's not necessary to use an additional variable "print_string" in this case.

Here's another way of looking at it:
>>> for index, letter in enumerate("hello"):
... print (f'index={index} letter={letter}')
...
index=0 letter='h'
index=1 letter='e'
index=2 letter='l'
index=3 letter='l'
index=4 letter='o'

Related

How to link elements from a string with numbers in Python?

I'd like to link elements from a string with numbers in Python.
Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0.
Then, when you give another string as an input, the corresponding numbers need to be printed.
What I tried:
# input
string = str(input())
# loop to link numbers with string input
number = -1
for letter in string:
number += 1
Now I'd like to link the first letter of the input string with the number 0 and so on.
E.g.:
string = "world"
than "w" = 0, "o" = 1, "r" = 2, "l" = 3 and "d" = 4.
And then when you give another string such as "lord" I want to get the following output:
3124
Because "lord" --> "l" = 3, "o" = 1, "r" = 2 and "d" = 4
I don't know how I can save these numbers to their corresponding letter.
a = "world"
tracker = dict()
for index, value in enumerate(a):
tracker[value] = index
b = "lord"
result = ""
for str_char in b:
result += str(tracker[str_char])
print(result)
There is built-in data structure that can store key value pairs and it is called
dictionary
You can make it as such:
string = "world"
letters_numbers = {}
numerator = 0
for char in string:
if char not in letters_numbers:
letters_numbers[char] = numerator
numerator += 1
then you can get another string, such as lord:
string2 = "lord"
numbers = []
for char in string2:
numbers.append(str(letters_numbers[char]))
print("".join(numbers)) # prints 3124
This way you can use words that has same letter multiple times and still get correct results.

How to count number of occurrences of a substring inside a string in Python?

I am attempting to write a code snippet that requests from the user to enter a string s and then a substring ss. The program will then have to count the number of occurrences of ss in s. For example if the user enters s = ‘azcbobobegghakl’ and ss = ‘bob’, then the program should print: Number
of times bob occurs is: 2.
Here is my code so far :
def count(s,ss):
Occurrence = 0
if ss in s :
for ss in s :
Occurrence += 1
return Occurrence
#Main program :
s = str(input("Choose a string: "))
ss = str(input("Choose a substring:"))
print ("Number of times " + str(ss) + " occurs is : " + str(count(s,ss)) )
My desired output would be this:
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2
But instead I get this :
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8
So can someone please help me modify this code to deliver the desire output? Thanks in advance
you can use count
print("hellohel".count("hel"))
2
If you want to count overlapping occurrences... maybe this can help
def countOverlapping(string, item):
count = 0
for i in range(0,len(string)):
if item in string[i:len(item)+i]:
count += 1
return count
print(countOverlapping("ehehe", "ehe"))
output should be...
2
How does that work?
as #SomeDude mentioned it uses what he calls a sliding window approach
we take the length of the substring and check if its in that "window" of the string each iteration:
is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1
You need to go for a sliding window approach to get count of substrings in a string.
example:
string : "ehehehe"
substring : "ehe"
start with first 3 ( because length of substring is 3 ) letters "ehe"- is it the substring we are looking for? - yes.
now leave the first letter "e" and combine letters "he" with the next letter "h" to form "heh" is it the substring we are looking for? - no
now leave the first letter "h" and combine letters "eh" with the next letter "e" to form "ehe" is it the substring we are looking for ? yes
do it till the end of the string and count number of "yes"s

Write a function that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string

Write a function called missing_letters that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string. The letters in the returned string should be in alphabetical order.
It should also use the global variable alphabet. It should use this global variable directly, not through an argument or a local copy. It should loop over the letters in alphabet to determine which are missing from the input parameter.
The function missing_letters should combine the list of missing letters into a string and return that string.
Write a loop over the strings in list test_miss and call missing_letters with each string. Print a line for each string listing the missing letters. For example, for the string "aaa", the output should be the following.
aaa is missing letters bcdefghijklmnopqrstuvwxyz
I tried my best to solve this. The program is working but not giving
the desired output.
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
for c in s:
i=0
while i < len(alphabet):
if alphabet[i] not in c:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
the program is giving appropriate output for any string with a single character, like - "b"
that is: b is missing letters acdefghijklmnopqrstuvwxyz
But for a string with multiple characters, like: "zzz" the output is:
zzz is missing letters aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyy
But I want:
zzz is missing letters abcdefghijklmnopqrstuvwxy
The set type already handles most of the work for you.
import string
def missing_letters(s):
return ''.join(sorted(set(string.lowercase) - set(s)))
If x and y are sets, then x - y is the set of items present in x but not in y. One you have the set of missing characters, you can sort them and re-join the sorted elements into a single string.
>>> set('abc') - set('a')
set(['c', 'b'])
>>> sorted(_)
['b', 'c']
>>> ''.join(_)
'bc'
Keeping with the spirit of what you have already defined. The issue is that you are testing each letter in the missing_letters function more than once. So you just want to check if the character (from the alphabet) is in the string. So take out the extra for loop which loops through the letters in the argument - like such
alphabet = 'abcdefghijklmnopqrstuvwxyz'
test_miss = ["b","zzz"]
def missing_letters(s):
missingAlphabets = ""
global alphabet
i = 0
while i < len(alphabet):
if alphabet[i] not in s:
missingAlphabets += alphabet[i]
i += 1
sortedmissingAlphabetslists = sorted(missingAlphabets)
sortedmissingAlphabets = ''.join(sortedmissingAlphabetslists)
return sortedmissingAlphabets
for i in test_miss:
print('{} is missing letters {}'.format(i,missing_letters(i)))
b is missing letters acdefghijklmnopqrstuvwxyz
zzz is missing letters abcdefghijklmnopqrstuvwxy
def has_duplicates(t):
t= histogram(t)
for i in t:
a=(t[i])
if a > 1:
return True
else:
return False
for i in test_dups:
f = has_duplicates(i)
if f == True:
print(i +' '+ 'has duplicates')
else:
print(i +' '+ 'has no duplicates')

Detect Repetition In a Letter

I'm writing a Hangman Program, and I'm basically done, I'm just stuck on one part. So you have to detect repetition in your input, i got that part done, but then i messes up with words that have the same letter in it.
For Example:
The Word is apple:
when I input a, it says well done, the letter is in the word and prints a----
but when I input p, it says well done as well but only prints the first p, so the output looks like this ap---
but i want it to detect all p in the word, for example : app--
here are my codes for that part:
def getGuessedWord():
position = word.index(letter.lower())
global words
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
You need to find all the positions of the letter in your word!
Iterate through your word(enumerate function returns the list of index and value) and check if the value is the letter your are searching for!
Then
modify your words string!
That is
def getGuessedWord(letter,words,word):
for position, ltr in enumerate(word):
if ltr == letter:
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
word='apple'
words='-'*len(word)
while '-' in words:
words = getGuessedWord(raw_input('Enter a letter : '),words,word)
Output:
Enter a letter : l
---l-
Enter a letter : e
---le
Enter a letter : a
a--le
Enter a letter : p
apple
Hope it helps!
Given, for example:
letter = 'p'
word = 'apple'
With this list comprehension:
[x==letter for x in word]
You can detect where is a certain letter is, if it is at all, in this example it would return:
[False, True, True, False, False]
Which corresponds with the fact that only the second and third letters in apple are "p".
Because True is 1 in Python, the same happens with 0 and False. So, if you want a numeric value you can just sum the values in the list, by doing:
sum([x==letter for x in word])
You could try this to verify the previous statement:
>>> True == 1
True
>>> False == 0
True
For a more detailed/specific answer, I'll need more information about how it is implemented.

Printing odd numbered characters in a string without string slicing?

I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.

Categories

Resources