Filtering Characters from a String [duplicate] - python

This question already has answers here:
Remove specific characters from a string in Python
(26 answers)
Closed 9 years ago.
I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed.
First thing is to iterate over str1 with a for loop, then compare to str2, to accomplish subtraction I should create a 3rd string in which to store the output but I'm a little lost after that.
def filter_string(str1, str2):
str3 = str1
for character in str1:
if character in str2:
str3 = str1 - str2
return str3
This is what I've been playing with but I don't understand how I should proceed.

Just use str.translate():
In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'
From the documentation:
string.translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
If -- for educational purposes -- you'd like to code it up yourself, you could use something like:
''.join(c for c in str1 if c not in str2)

Use replace:
def filter_string(str1, str2):
for c in str2:
str1 = str1.replace(c, '')
return str1
Or a simple list comprehension:
''.join(c for c in str1 if c not in str2)

Related

Python Check array item in string [duplicate]

This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 2 years ago.
str1 = 'Thank you very much. It was really great help for me'
str2 = 'Yes, I am'
str3 = 'No, It wasn`t'
arr = ['it', 'no', 'jack']
if str1 in arr => true
if str2 in arr => false
if str3 in arr => true
i don't care upper or lower.
i want to check that i saved array and check string value if there is a word.
how can i check it?
i tried
print(arr in str)
but error occored
'in ' requires string as left operand, not list
somebody help me
If I understand correctly what is your desired test here:
print(any(s.lower() in str1.lower() for s in arr))
print(any(s.lower() in str2.lower() for s in arr))
print(any(s.lower() in str3.lower() for s in arr))
Try any method :)
print(any(i in arr for i in str1.lower())
print(any(i in arr for i in str2.lower())
print(any(i in arr for i in str3.lower())
As the error suggests, it is the other way around:
print(str1 in arr)
print(str2 in arr)
print(str3 in arr)
Consider looking at the traceback and try to make more sense out of it. Most issues can be debugged quite easily from the traceback and googling on the specific issue.
However, looks like you are trying to check any word inside arr lies in your particular string str, you can do this:
print(any(s in str1 for s in arr))
Since you're apparently only trying to match words but not punctuations, it's easiest to use a regex pattern with desired words joined as an alternation pattern, enclosed with word boundary checks on both ends:
import re
re.search(rf"\b({'|'.join(arr)})\b", str1, re.I)
This returns a truthy value for str1 and str3, and a falsey value for str2, from your sample inputs.
Just do this if you don't care about upper or lower:
print(str1 in arr, str2 in arr, str3 in arr)

TypeError: ord() expected a character, but string of length 2 found

I met a awkward problem.
TypeError: ord() expected a character, but string of length 2 found
my code:
for c in input_s:
if ord('a') <= ord(c.lower()) <= ord('z'):
e_count += 1
I expected that for c in input_s which is string and the c always character is assinged. This happens very rarely, so very hard to regenerate the problem. Is there any case the c variable has length2 string?
Even if c is one code point, c.lower() may be multiple. For example, with U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE, which lowercases to a regular i followed by a U+0307 COMBINING DOT ABOVE:
>>> x = '\u0130'
>>> len(x)
1
>>> len(x.lower())
2
The same can happen with c.upper(). One particularly famous case is the eszett:
>>> x = 'ß'
>>> x.upper()
'SS'
>>> len(x)
1
>>> len(x.upper())
2
Your ord(c.lower()) call is fundamentally incorrect. If you want to test whether a character is an uppercase or lowercase ASCII letter, you can use isascii to test whether a character lies in the 0-127 ASCII range and isalpha to test whether it's an alphabetical character. You can also use these methods to test whole strings at once. For example,
if input_s.isascii() and input_s.isalpha():
...
would test whether input_s is a nonempty string containing only ASCII alphabetical characters. (The "nonempty" part is because isalpha returns False for empty strings.)
isascii is very new, introduced in Python 3.7. If you have to support older Python versions, you can test individual characters for ASCII-ness with '\x00' <= c <= '\x7f' or 0 <= ord(c) <= 127, or you can hardcode which ranges are ASCII letters and test characters for ASCII-letter-ness with 'A' <= c <= 'Z' or 'a' <= c <= 'z'.
You might be using tuple(or any sequence) for input_s.
If the first element in your sequence is a string of length 2, you would get the same error.
If its the case, you use a string(or split the sequence), the code should work fine.

How to check if 2 strings contain a matching letter in Python? [duplicate]

This question already has answers here:
Evaluate multiple variables in one 'if' statement?
(8 answers)
Closed 7 years ago.
Say i have 2 strings that both contain the letter B, How would i check to confirm that both strings contain the same letter?
I tried doing:
myString1 = 'JILL'
myString2 = 'BOB'
if 'B' or 'K' in myString1 and myString2:
print('both strings contain the same letter')
The print statement is still reached even though myString1 does not contain the letters K or B.
I would think that the "and" operator would be like saying both variables need to contain the same letter for the print statement to be reached but this is not the case, Instead the print statement is always reached regardless of weather or not both strings contain the same letter.
You can use any with as many characters as you want to check:
to_check = ('B', 'K')
if any(c in myString1 and c in myString2 for c in to_check):
Your code fails as if 'B' is always True, you are checking if B is not a falsey value which for all but an empty string would be True if you were to write out it out explicitly without using any then it would be:
if 'B' in myString1 and B' in myString2 or 'K' in myString1 and 'K' in myString2:

How to find out if str has any number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a question. If I have a string, for example:
str1 = 'Wazzup1'
and numbers:
nums = '1234567890'
I need a code that will look into str1 and tell me if it has any number(not all of them). Please help.
Use any and a generator expression:
any(x in nums for x in str1)
Below is a demonstration:
>>> str1 = 'Wazzup1'
>>> nums = '1234567890'
>>> any(x in nums for x in str1)
True
>>>
Note that the above is for when you have a custom set of numbers to test for. However, if you are just looking for digits, then a cleaner approach would be to use str.isdigit:
>>> str1 = 'Wazzup1'
>>> any(x.isdigit() for x in str1)
True
>>>
Use the any function, which returns a Boolean which is true iff at least one of the elements in the iterable is true.
string = 'Wazzup1'
result = any(c.isdigit() for c in string)
print(result) # True
As most Python programmers will tell you, the most concise way to do this is using:
any(x in nums for x in str1)
However, if you're new to Python or need a better grasp of the basics of string manipulation, then you should learn how to do this using more fundamental tools.
You can access the individual elements of a string, list, tuple, or any other iterable in Python using square brackets around an index. The characters of a string are indexed starting from 0 (e.g. "hello"[0] gives "h").
Using a for loop, the solution is easier to understand for a Python newbie than the above-mentioned any solution:
result = False
for i in range(len(str1)):
if str1[i] in nums:
result = True
A Python for loop can also iterate directly over the elements of the string:
result = False
for x in str1:
if x in nums:
result = True
In the first code snippet in this post, the expression x in nums for x in str1 uses Python's list comprehension feature. This goes through every element x of str1 and finds the result of x in nums. any(x in nums for x in str1) returns True if (and only if) at least one of these results is True (meaning a numerical digit is in str1). This is much like the second for loop example given in this post, and many Python programmers choose this option because it is concise and still understandable by other Python programmers.
You can use any() and string.digits to check whether the string contain a digit:
import string
if any(x in string.digits for x in str1):
pass
You could also use a regular expression:
>>> str1 = 'Wazzup1'
>>> import re
>>> bool(re.search(r'\d', str1))
True
Note: there might be a difference in how c.isdigit(), c in nums, int(c) and \d define what is a digit due to locale or Unicode.

<function>(str1, str2) calling them separately

First off, this IS homework, so I am not expecting any direct answers. I need to take two strings defined by a function (semordnilap(str1, str2)) and I need to see if they are equal when one is reversed. I was wondering if I can call these separately out of the function with semordnilap(str1[0:1) == semordnilap(str2[-1]) I tried this a few ways and I must not be thinking about it correctly, plus of course there is the kicker of trying to do this recursively. Any advise or direction would be helpful.
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap
False otherwise.
'''
if len(str1) != len(str2):
return False
if len(str1) <= 1 or len(str2) <= 1:
return False
if semordnilap(str1[0]) != semordnilap(str2[-1]):
return False
else:
return True
This is what I have so far, getting error of TypeError: semordnilap() takes exactly 2 arguments (1 given)
Given two strings str1 and str2, the easiest way to compare if one is equal to the reverse of the other is by using slicing:
str1 = 'racecar'
str2 = 'racecar'
str1 == str2[::-1]
Out[57]: True
Which is really just checking if str1 is a palindrome (i.e. a reverse of itself).
If you really want to use recursion, you also want to be using slicing: check if str1[0] == str2[-1], and then recursively call your function on str1[1:] and str2[:-1].
The [::-1] syntax is extended slicing syntax, which is valid for strings as well as lists and other sequences.
To reverse a string you use 'this is a string'[::-1].
[::-1] Is slice notation which says include everything from the start to the end of the string but do it in reverse.
'abcdefghijk'[6:1:-2] outputs 'gec' because it goes from the 6th index (starting with 0) up to but not including the first index, in reverse steps of 2.
Read up more on slice notation:Explain Python's slice notation, http://docs.python.org/2.3/whatsnew/section-slices.html
def semordnilap(str1, str2):
if str1 == str2[::-1]: return True
else: return False
One way to do it recursively:
def semordnilap(str1, str2):
if not (len(str1) or len(str2)): return True
if not (len(str1) and len(str2)): return False
if str1[0] != str2[-1]: return False
return semordnilap(str1[1:], str2[:-1])
The first line checks if both strings are empty (0 evaluates to False, any other number is True). len(str1) returns the length as an integer.
Then it checks if only one of the strings is empty in which case they are not equal.
Then it checks if the first letter is the same as the last letter.
Then it repeats the process with the each string (minus the first letter of str1 and minus the last letter of str2). It goes until one of the base cases is reached. The base case is what is returned. So it will only return True when then first letter was equal to the last letter each round until both strings ran out of characters at the same time.

Categories

Resources