Counting occurence within a string Python - python

I am writing a code to count the occurrences of each letter within a string. I understand that it has been asked and answered Count occurrence of a character in a string, however I cannot figure out why it will not count when I use it.
def percentLetters(string):
string = 'A','B'
print string.count('A')
print string.count('B')
If I was to input percentLetters('AABB'), I would anticipate receiving A=2 and B=2 but am having no such luck. I tried using an if statement earlier however it would not print anything at all
def percentLetters(string):
string='A','B'
if 'A':
print string.count('A')
if 'B':
print string.count('B')
This doesn't work either. Anyone who might have some insight it would be helpful

Don't reassign string inside the function and better to not use string as a variable name at all.
def percentLetters(s):
print s.count('A')
print s.count('B')
percentLetters('AABB')
2
2
string = 'A','B' means you set the string variable to a tuple containing just ("A","B"), it is not pointing to the string you pass in.
In [19]: string = 'A','B'
In [20]: string
Out[20]: ('A', 'B')

Because count is a method/module (whatever it's called in python) for string, the way you do it,
myString ='A','B'
myString is a tuple, not a string.

first, here is the correct version of your code:
def percentLetters(string):
print string.count('A')
print string.count('B')
second, you don't use two strings in an assignment to one variable unless you want to make it a string tuple.

Related

Why do sequence for loops don't seem to work well in Python?

I'm trying to convert every string in a list to it's lowercase format using this function:
def lower_list(strings):
for string in strings:
string = string.lower()
return strings
But this implementation is not working, however when using the range funtion and I iterate using an index:
def lower_list(strings):
for i in range(len(strings)):
strings[i] = strings[i].lower()
return strings
I do get every element on my list converted to lowercase:
> print(lower_list(mylist))
['oh brother where art thou', 'hello dolly', 'monsters inc', 'fargo']
But with the first implementation I get the original list with Uppercase values, am I missing something important in how the for loop works?
In the first case, all you are doing is storing the lowercase value in a variable, but the list is untouched.
In the second case, you are actually updating the value in the list at that index.
You can also use a lambda function here:
def lower_list(strings):
return list(map(lambda x: x.replace(x, x.lower()), strings))
List comprehension is the easiest and the best:
def lower_list(strings):
return [string.lower() for string in strings]
The reason the first one does not work is that it is not actually modifying the value inside of the list, rather it is just affecting a copy of the value in the list. When you use the index-based function, it modifies the list itself.
def lower_list(strings):
for string in strings:
index_of_string = strings.index(string)
string = string.lower()
strings[index_of_string] = string
return strings
If you want the first one to work, maybe you can try something like that, but thats a bad way of doing it, just showing it as an example so maybe you'll understand better. You need the index of that string so you can replace it in the list. In your first attempt, you do not replace anything in the list.

Checking data type in a conditional statement

I want to print a character from a string if it is an integer.
This is a simplified and specific sample code which I wrote after zeroing-in on the problem in a code I was writing for a Kata in Codewars. While the Kata is not relevant here, I can't seem to figure out how to use data type in a conditional statement (something like if type(char) == int).
string = "th3is i1s anot4her ra2ndom strin5g"
for word in string:
for char in word:
if type(char) == int:
print(char)
You never split your string into words, so the outer loop makes no sense.
You are iterating over characters, which are length 1 strings. The type of a length 1 string is never equal to int.
You can use the str.isdigit method.
Rewritten code with a single loop:
for c in string:
if c.isdigit():
print(c)
As a oneliner:
print('\n'.join(c for c in string if c.isdigit()))
I think isdigit() can work, also you can use regex.
https://www.w3schools.com/python/ref_string_isdigit.asp
You are partially on the right track with using the type keyword, however, if you type in
type(<some variable>)
into the interpreter, you will always get an output similar to the form "<class '<type'>"
where <type> is the type of your variable. You can use the practically with this code (it's an example so modify it for your purpose):
myvar = "some python string"
if type(myvar) == "<class 'str'>":
# true
print("Is a string")
now as you can imagine, this program would output
>>> Its a string
You can make this work with any type by changing the str part of the "<class 'str'>" block to the type that you are looking for (for example: "<class 'int'>" for integers).
Hope this helps!
This can be done with regular expressions, You can import re module in Python to use regular expressions :
import re
sentences = "th3is i1s anot4her ra2ndom strin5g"
num = re.findall("[0-9]", sentences)
print(num)
Basically, this code will return all numerical values in that string
Don’t worry.. Everybody who is a master programmer today was once a beginner and therefore would have had all obvious basic questions :).
You can use, str.isnumeric() boolean check. By using that you can avoid the second for loop since the second for loop doesn’t actually make sense here.
Here is the revised code-
string = "th3is i1s anot4her ra2ndom strin5g"
for char in string:
if char.isnumeric():
print(char)

How can I replace a character with a number in a string?

How do I place a variable in .replace() in python. For example:
x = 2
example = example2.replace("1", x)
I think its clear what I am looking for, I just have no clue how to do it.
My comments are based on Python v2.7:
In your code, "x" is assigned a integer value, they do not have replace method.
Instead, if "x" had carried normal string, then replace is available and this is how it works:
var2 = "palindrome syndrome"
print var2.replace("drome", "pal", 2)
Output:
palinpal synpal
In the statement, var2.replace, there are three arguments:
"drome" is the substring to find and replace with new string "pal" and do this for two occurrences of "drome".

Error:string index out of range, defining a function

I'm practicing coding on codingbat.com since I'm a complete beginner in python, and here is one of the exercises:
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
Here is my attempt at defining the function string_bits(str):
def string_bits(str):
char = 0
first = str[char]
for char in range(len(str)):
char += 2
every_other = str[char]
return (first + every_other)
Running the code gives an error. What's wrong with my code?
A different approach, with an explanation:
If you need to handle a sentence, where spaces would be included, you can do this using slicing. On a string slicing works as:
[start_of_string:end_of_string:jump_this_many_char_in_string]
So, you want to jump only every second letter, so you do:
[::2]
The first two are empty, because you just want to step every second character.
So, you can do this in one line, like this:
>>> " ".join(i[::2] for i in "Hello World".split())
'Hlo Wrd'
What just happened above, is we take our string, use split to make it a list. The split by default will split on a space, so we will have:
["Hello", "World"]
Then, what we will do from there, is using a comprehension, iterate through each item of the list, which will give us a word at a time, and from there we will perform the desired string manipulation per i[::2].
The comprehension is: (documentation)
i[::2] for i in "Hello World".split()
Finally, we call "".join (doc), which will now change our list back to a string, to finally give us the output:
"Hlo Wrd"
Check out the slicing section from the docs: https://docs.python.org/3/tutorial/introduction.html
The problem is that the char += 2 returns a value greater than len(str) as len(str)-1 (the range) + 2 is longer than the string. You could do:
def string_bits(string):
if len(string) == 2:
return string[0]
result = ''
for char in range(0,len(string),2):#range created value sin increments of two
result += string[char]
return result
A more succinct method would be:
def string_bits(string):
return string[::2]
You should avoid using 'str' as a variable name as it is a reserved word by Python.
Ok, for me:
You should not use str as a variable name as it is a python built-in function (replace str by my_str for example)
For example, 'Hello' length is 5, so 0 <= index <= 4. Here you are trying to access index 3+2=5 (when char = 3) in your for loop.
You can achieve what you want with the following code:
def string_bits(my_str):
result = ""
for char in range(0, len(my_str), 2):
result += my_str[char]
return result
The error you are getting means that you are trying to get the nth letter of a string that has less than n characters.
As another suggestion, strings are Sequence-types in Python, which means they have a lot of built-in functionalities for doing exactly what you're trying to do here. See Built-in Types - Python for more information, but know that sequence types support slicing - that is, selection of elements from the sequence.
So, you could slice your string like this:
def string_bits(input_string):
return input_string[::2]
Meaning "take my input_string from the start (:) to the end (:) and select every second (2) element"

Python Replace Character In List

I have a Python list that looks like the below:
list = ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
I access the letter in the index I want by doing this:
list[y][x]
For example, list[1][10] returns F.
I would like to replace F with a value. Thus changing the string in the list.
I have tried list[y][x] = 'o' but it throws the error:
self.map[y][x] = 'o'
TypeError: 'str' object does not support item assignment
Can anybody help me out? Thanks.
As #Marcin says, Python strings are immutable. If you have a specific character/substring you want to replace, there is string.replace. You can also use lists of characters instead of strings, as described here if you want to support the functionality of changing one particular character.
If you want something like string.replace, but for an index rather than a substring, you can do something like:
def replaceOneCharInString(string, index, newString):
return string[:index] + newString + string[index+len(newString):]
You would need to do some length checking, though.
Edit: forgot string before the brackets on string[index+len(newString):]. Woops.
Since python strings are immutable, they cannot be modified. You need to make new ones. One way is as follows:
tmp_list = list(a_list[1])
tmp_list[10] = 'o' # simulates: list[1][10]='o'
new_str = ''.join(tmp_list)
#Gives |oooooooococooooooooi
# substitute the string in your list
a_list[1] = new_str
As marcin says, strings are immutable in Python so you can not assign to individual characters in an existing string. The reason you can index them is that thay are sequences. Thus
for c in "ABCDEF":
print(c)
Will work, and print each character of the string on a separate line.
To achieve what you want you need to build a new string.For example, here is a brute force approach to replacing a single character of a string
def replace_1(s, index, c)
return s[:index] + c + s[index+1:]
Which you can use thus:
self.map[y] = replace_1(self.map[y], x, 'o')
This will work because self.map is list, which is mutable by design.
Let use L to represent the "list" since list is a function in python
L= ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
L[1]='|oooooooococooooooooi'
print(L)
Unfortunately changing a character from an object (in this case) is not supported. The proper way would be to remove the object and add a new string object.
Output
['|wwwwwwwwadawwwwwwwwi', '|oooooooococooooooooi']

Categories