How to match exactly two same characters in a string like '4003', '1030'.
import re
s='1030'
if re.search('0{2}',s):
print(True)
But the above code matches only '1002' butnot '1030'
Assume you don't have to use regex:
Note that a string with 4 characters have exactly a pair of duplicating character if and only if it has 3 unique characters. So:
Make a set of its characters
Check if there are 3 distinct elements in the set.
Do you HAVE to use regex? Just use .count()
>>> '1002'.count('0')
2
>>> '1030'.count('0')
2
>>> '2002200220'.count('20')
3
This code sniped just checks if f.e. index 3 from the string number1 is equal to the index 3 from the string number2.
number1 = '1002'
number2 = '1030'
counter = 0
for i in number1:
if number1[counter] is number2[counter]:
print("It's a match")
counter = counter + 1
Related
I'm looking to take in two strings via user input and to call a function to match each character from the first string to that of the second string, and count them. So String 1 = bad and String 2 = bed would return a count of 2 characters matched
def occurrences(text1, text2):
count = 0
for c in firstword :
if c == secondword :
count += 1
return True
return False
firstword = input("Enter first word")
secondword = input("Enter second word")
occurrences(firstword, secondword)
Passing the two strings into the function returns false, even if they're exactly the same word. Just wondering where I'm going wrong with the for loop here, why is the if statement not matching the strings and counting.
Thanks
for c in firstword :
if c == secondword :
You're iterating over the first string character by character (for c in firstword), and you match that one character to the entire second string secondword. Not to mention that:
you're using the outer variables firstword and secondword instead of the function parameters text1 and text2
your function only returns True or False, at no point does it even attempt to return a count
you return True right on the first match, if there ever was one, so it could never progress beyond 1
To compare two strings character by character, you need to iterate both string in parallel. The best way to do that is zip:
count = 0
for c1, c2 in zip(text1, text2):
if c1 == c2:
count += 1
Which can be made into a one-liner with sum:
def occurrences(text1, text2):
return sum(c1 == c2 for c1, c2 in zip(text1, text2))
Silly bonus round, if you want to be really fancy and functional about it:
from operator import eq
from itertools import starmap
def occurrences(text1, text2):
return sum(starmap(eq, zip(text1, text2)))
In function when you arrive on return, the function is ending so when you want counting and end of for-loop return your counter don't set return in for-loop.
try this:
def occurrences(text1, text2):
count = 0
for c in firstword :
if c in secondword :
count += 1
return count
firstword = input("Enter first word : ")
secondword = input("Enter second word : ")
occurrences(firstword, secondword)
output:
Enter first word : bad
Enter second word : bed
2
This question already has answers here:
Convert letters to numbers
(5 answers)
Closed 1 year ago.
message = str(input())
for i in message:
if i == "a": i = 1
if i == "b": i = 2
print(i)
ect.
I am trying to create a code generator where the user inputs a string eg. "hello" and it is converted to a number code by assigning each letter a number, based on their position in the alphabet. 1 = a, 2 = b and so on. The method I am currently using is very long - are there other ways to do this to avoid this issues?
How can I print the answer together, without the numbers being on multiple lines eg. 1 2 3 21 19
Use string lib:
import string
[string.ascii_lowercase.index(s)+1 for s in 'hello'.lower()]
Output:
[8, 5, 12, 12, 15]
You could convert the letter to its ASCII code value, calculate its position, then add the position of the letter to the string and print the string.
To get the numeric value of a char, use the ord() method, to get a character from a numeric value, use the char() method.
Link to ASCII table
import string
low_letter = list(string.ascii_lowercase)
now you have a list of all letters in order
so...
message = str(input())
for i in message:
print(low_letter.index(i))
now you have the index
and in case you need the upper case :
upper_case = list(string.ascii_uppercase)
```
msg = str(input())
for char in msg:
print(ord(char) - ord('a') + 1)
The idea is to convert each character into ASCII using ord() in python and subtract it with the ASCII of 'a' and + 1
So consider "hello" string :
The output will be :
hello
8
5
12
12
15
Note : Here we subtract the ASCII of the character with the ASCII of character 'a' in order to get the correct Position as in Alphabetical order.
Eg : h
Ascii of h = 104
Ascii of a = 97
So our required answer = Ascii of h - Ascii of a + 1
= 104 - 97 + 1 = 8
And if we look the alphabetical order - a,b,c,d,e,f,g,h -> h is the 8th character
Hope this helps you. Thank you
Just create a dictionary that maps 'a' to 1, 'b' to 2, etc
from string import ascii_lowercase
mapping = dict(zip(ascii_lowercase, range(1, 27)))
And use it like this
numbers = [mapping[char] for char in message if char in mapping]
You need to check if each character is in the alphabet, otherwise you'll get an error. If you also want to cover the uppercase letters, change message to message.lower() in the loop line.
Using index() every iteration is inefficient, even though in this case it won't matter much because you're searching through at most 26 letters. But in general it's not a good strategy. Dictionary lookup is O(1).
Let's say I have a string a = 31 4 5 + + and a string b = 31 4 5 ++. I need to check that all numbers and operators in the string are delimited by at least one white space. Therefore, string a is correct, string b incorrect. c = 31 4 5+ + is also incorrect. Is there a way how to check for this? I could not come up with anything reasonable.
You can check it through following steps -
Break string into list using .split()
Check whether items in list whose length is more than 1 is numeric or not.
Code snippet:
def is_valid_string(st, delimiter = ' '):
lst = st.split(delimiter) # create list of chars separated by space
for item in lst:
if len(item) > 1 and not item.isdigit():
return False
return True
In case if you are considering float numbers you can use item.replace('.','',1).isdigit()
First thing to do would be splitting the strings by the whitespaces into "words", so something like words = a.split() (split's delimitor is a whitespace by default so no need for arguments)
I'm guessing you're only gonna use integers or floats and a set of operators like adding, substraction, multiplication and division, so one thing that you could do is check if you can cast the words into numbers with int or float and if you can't, check if the word is in your operators set, so something like:
a = "31 4 5 + +"
operators = ["+", "-", "*", "/"]
# Every string is valid by default
valid = True
words = a.split() # ["31", "4", "5", "+", "+"]
for word in words:
# try to cast word into a number
try:
float(word)
except:
# if you can't, check if it's an operator
if word not in operators:
valid = False #if it's not, the string isn't valid
if valid:
print("String is valid")
else:
print("String is not valid")
More complex stuff like equations and variables is obviously more difficult to code.
EDIT: python's isdigit() checks if a string is a number and it is more simple than a try block for casting the string, but it doesn't check for floats, which won't be valid. (you could still replace decimal points by numbers)
Try use regex ^((\d+|[+*/-])(\s+|$))+$. It matches more or more items, each of which is either a number (\d+) or an operator ([+*/-]), followed by either one or more spaces (\s+) or the end of string ($). The ^ at the beginning and ($) at the end force the regex match the whole string. Example:
>>> import re
>>> a = '31 4 5 + +'
>>> b = '31 4 5 ++'
>>> c = '31 4 5+ +'
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', a))
<re.Match object; span=(0, 10), match='31 4 5 + +'>
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', b))
None
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', c))
None
beginner here. Trying to figure out how I can define a function that counts the total number of occurrences of certain characters in a string. Say, we want to count the number of occurrences of the letters a and b. I need to do it within a for loop. What I have so far is this. Please let me know what I can do to make this work!
#define functions
def ch_count(word):
total=0
for letter in word:
if letter==L1:
total=total+1
return total
#main program
L1=["a","e","y"]
print(ch_count("Merry Christmas")
You can try using a default dictionary. Unlike a normal dictionary, it provides a default value is a key does not exist in a dictionary.
from collections import defaultdict
string = 'quick brown fox'
letter_count = defaultdict(int)
for letter in string:
letter_count[letter] += 1
print(letter_count)
you could write a function which takes 2 arguments. The string to check, and the letter that we want to use to count occurrencies in the string.
# I will use a as a default letter
def count_occurrencies(s, letter='a'):
return sum([i == letter for i in s])
You can use sum:
string = 'Some test string'
c = 'a'
sum(x == c for x in string)
Checking for multiple characters instead:
c = 'abc'
sum(x in c for x in string)
Or you can use collections.Counter to find the count of each character:
from collections import Counter
counts = Counter(string)
counts[letter]
I wrote the function that converts the string in argument to number. If the string does not contain number the cycle breaks and the new variable with numbers is printed.
If the argument is "123" the function returns 6. I don't want to return the sum, just placing every number in a row. How do I accomplish the result 123? I don!t know what to use instead of string2 += float(c).
def try_parse(string):
string2=0
for c in string:
if c.isdigit() == True:
string2 += float(c)
else:
break
return string2
I modified your code:
def try_parse(string):
string2 = ""
for c in string:
if not c.isdigit() and c != '.':
break
string2 += c
return string2
You can see that now I use string2 as a string and not an int (When the + sign is used on an int you sum, and with a string + is used for concatenation).
Also, I used a more readable if condition.
Update:
Now the condition is ignoring the '.'.
Tests:
>>> try_parse('123')
'123'
>>> try_parse('12n3')
'12'
>>> try_parse('')
''
>>> try_parse('4.13n3')
'4.13'
Note
The return type is string you can use the float() function wherever you like :)
You need to use a string for string2, and str instead of float.
You want string2 = "", and string2 += c. (You don't need to call str on c because it is already a string.)
You could leave the conversion to a number to Python (using int(), rather than float(); you only filter on digits), and only worry about filtering:
def try_parse(string):
digits = []
for c in string:
if c.isdigit():
digits.append(c)
return int(''.join(digits))
but if you really want to build a number yourself, you need to take into account that digits are not just their face value. 1 in 123 does not have the value of one. It has a value of 100.
The easiest way then to build your number would be to multiply the number you have so far by 10 before adding the next digit. That way 1 stays 1, and 12 starts as 1 then becomes 10 as you add the 2, etc:
def try_parse(string):
result = 0
for c in string:
if c.isdigit():
result = result * 10 + int(c)
return result