Multiple replacements - python

I want the user to be able to input more than one character they want to remove. It works but only if one character is entered.
string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
replacements = [(removing_chars, "")]
for char, replacement in replacements:
if char in string:
string = string.replace(char, replacement)
print(string)

The issue is that you're treating removing_chars as if it is always a single character.
For example, if removing_chars is 'abc', then replacements will be [('abc', '')], when it should be [('a', ''), ('b', ''), ('c', '')] instead.
To fix this, try using a list comprehension to loop over each character in removing_chars and create a replacement tuple. Like this:
string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
replacements = [(char, "") for char in removing_chars]
for char, replacement in replacements:
if char in string:
string = string.replace(char, replacement)
print(string)

when you loop over replacements, char takes removing_chars as value. Then, when you check if char in string, Python checks if removing_chars is a substring of string. To actually remove the characters separately, you have to loop over removing_chars in order to get the individual characters.

I would use a combo of maketrans & translate :
string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
​
out = string.translate(str.maketrans("", "", removing_chars))
​
Output :
print(out)
#Please enter a sentence: StacxkOverfLlow
#Please enter the characters you would like to remove: xL
#StackOverflow

This may be an excellent place to use regular expressions. We can insert the characters to remove string into aa string wrapped in [ and ] to create a character class, and then use sub to replace any occurrences of those characters with ''.
>>> import re
>>> s = input("line of text: ")
line of text: hello world foo bar baz
>>> r = input("characters to remove: ")
characters to remove: abc
>>> rx = re.compile(rf"[{r.strip()}]")
>>> rx
re.compile('[abc]')
>>> rx.sub('', s)
'hello world foo r z'
Of course, to avoid issues with special characters that are significant in regular expression character classes, you may wish to use re.escape. E.g.
>>> rx = re.compile(rf"[{re.escape('a-c')}]")
>>> rx
re.compile('[a\\-c]')

Related

Python- How to strip a sting for more than one character with user inputs [duplicate]

This question already has answers here:
Best way to replace multiple characters in a string?
(16 answers)
Closed last month.
For homework, I have to design a program that accepts a string as user input.
Users must also input some characters (more than one) that want to remove from the orinal string:
user input = The quick brown fox jumps over the lazy dog.
characters to strip = a,e,i,o,u
result = Th qck brwn fx jmps vr th lzy dg.
I would appreciate any help. Please keep the code simple.
This exercise is about string handling.
I have covered loops and strings.
NO lists nor lists comprehensions nor Dictionaries nor functions.
I would appreciate if you could keep your code related to the topics I have covered.
Thank you
string = input('Please type something: ')
characters = input('What characters would you like to strip: ')
for char in string:
for j in characters:
new_string = string.replace(char, '')
print(new_string)
You don't need to iterate over the string, only over the characters to remove
string = 'The quick brown fox jumps over the lazy dog.'
characters = 'aeiou'
new_string = string
for char in characters:
new_string = new_string.replace(char, '')
print(new_string) # Th qck brwn fx jmps vr th lzy dg.
Explaination, you need to iterate through all the character in the string and for each individual character see if that character is in banned characters or not.
if present there then igonre any processing on that character otherwise, add that character to a list
once whole string is processed then, to make the list of character to string back again use str.join method
this is code
string = 'The quick brown fox jumps over the lazy dog.'
characters = set('aeiou')
# store the character which are not to removed
string_characters =[]
for char in string:
# checking if letter in string is present in character or not in O(1) time
if char not in characters:
string_characters.append(char)
new_string = ''.join(string_characters) # use join function to convert list of characters to a string
print(new_string)
Easier way to do this, No need to do with function.
_string = input("Please type something: ")
if _string == 'x':
exit()
else:
newstring = _string
print("\nRemoving vowels from the given string")
vowels = ('a', 'e', 'i', 'o', 'u')
for x in _string.lower():
if x in vowels:
newstring = newstring.replace(x,"")
print(newstring)
Result:
Th qck brwn fx jmps vr th lzy dg
Or Using oneliners:
_string = input("Enter any string: ")
remove_str = ''.join([x for x in _string if x.lower() not in 'aeiou'])
print(remove_str)

Space between each character in python

I need a simple python code that lets you enter text and shows it with space between each character.
I have made something like this and it works but now I don't know how to make it with spaces
text = input("text: ")
print(f"{text}")
text = input("text: ")
text = ' '.join(list(text))
print(text)
text = input("enter text here")
words=text.split()
output=""
for word in words:
for letter in word:
output = output + letter + " "
print(output)
As mentioned in the comments, you are looking for the join method of a string. It takes an iterable and concatenates it together using the string as separator. As a string is an iterable itself you can simply do
' '.join('Hello')
>>> H e l l o

python regex matching "ab" or "ba" words

I tried matching words including the letter "ab" or "ba" e.g. "ab"olition, f"ab"rics, pro"ba"ble. I came up with the following regular expression:
r"[Aa](?=[Bb])[Bb]|[Bb](?=[Aa])[Aa]"
But it includes words that start or end with ", (, ), / ....non-alphanumeric characters. How can I erase it? I just want to match words list.
import sys
import re
word=[]
dict={}
f = open('C:/Python27/brown_half.txt', 'rU')
w = open('C:/Python27/brown_halfout.txt', 'w')
data = f.read()
word = data.split() # word is list
f.close()
for num2 in word:
match2 = re.findall("\w*(ab|ba)\w*", num2)
if match2:
dict[num2] = (dict[num2] + 1) if num2 in dict.keys() else 1
for key2 in sorted(dict.iterkeys()):print "%s: %s" % (key2, dict[key2])
print len(dict.keys())
Here, I don't know how to mix it up with "re.compile~~" method that 1st comment said...
To match all the words with ab or ba (case insensitive):
import re
text = 'fabh, obar! (Abtt) yybA, kk'
pattern = re.compile(r"(\w*(ab|ba)\w*)", re.IGNORECASE)
# to print all the matches
for match in pattern.finditer(text):
print match.group(0)
# to print the first match
print pattern.search(text).group(0)
https://regex101.com/r/uH3xM9/1
Regular expressions are not the best tool for the job in this case. They'll complicate stuff way too much for such simple circumstances. You can instead use Python's builtin in operator (works for both Python 2 and 3)...
sentence = "There are no probable situations whereby that may happen, or so it seems since the Abolition."
words = [''.join(filter(lambda x: x.isalpha(), token)) for token in sentence.split()]
for word in words:
word = word.lower()
if 'ab' in word or 'ba' in word:
print('Word "{}" matches pattern!'.format(word))
As you can see, 'ab' in word evaluates to True if the string 'ab' is found as-is (that is, exactly) in word, or False otherwise. For example 'ba' in 'probable' == True and 'ab' in 'Abolition' == False. The second line takes take of dividing the sentence in words and taking out any punctuation character. word = word.lower() makes word lowercase before the comparisons, so that for word = 'Abolition', 'ab' in word == True.
I would do it this way:
Strip your string from unwanted chars using the below two
techniques, your choice:
a - By building a translation dictionary and using translate method:
>>> import string
>>> del_punc = dict.fromkeys(ord(c) for c in string.punctuation)
s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
>>> s = s.translate(del_punc)
>>> print(s)
'abolition fabrics probable test case bank halfback 1ablution'
b - using re.sub method:
>>> import string
>>> import re
>>> s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
>>> s = re.sub(r'[%s]'%string.punctuation, '', s)
>>> print(s)
'abolition fabrics probable test case bank halfback 1ablution'
Next will be finding your words containing 'ab' or 'ba':
a - Splitting over whitespaces and finding occurrences of your desired strings, which is the one I recommend to you:
>>> [x for x in s.split() if 'ab' in x.lower() or 'ba' in x.lower()]
['abolition', 'fabrics', 'probable', 'bank', 'halfback', '1ablution']
b -Using re.finditer method:
>>> pat
re.compile('\\b.*?(ab|ba).*?\\b', re.IGNORECASE)
>>> for m in pat.finditer(s):
print(m.group())
abolition
fabrics
probable
test case bank
halfback
1ablution
string = "your string here"
lowercase = string.lower()
if 'ab' in lowercase or 'ba' in lowercase:
print(true)
else:
print(false)
Try this one
[(),/]*([a-z]|(ba|ab))+[(),/]*

How to check if last character is integer in raw_input

basically i want the script to check the last digit of the raw_input to see if it's integer or not. if integer print true, else print false
here is the code:
word = raw_input("input your alphanumeric word:")
end = re.search(r'\d+$', word)
if end is not None:
print "numeric digit should be last"
else
print "true"
Regex is an overkill for problems as simple as this. Simply index the last element word[-1] and check if its a digit via the builtin String method str.isdigit
word[-1].isdigit()
Note, you may have to consider the fact that the word may be an empty string and have to handle it appropriately.
bool(word) and word[-1].isdigit()
or as suggested by #iCodez use slicing instead of indexing, as slicing would not throw index error for empty string
word[-1:].isdigit()
Example
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:asdf
>>> bool(word) and word[-1].isdigit()
False
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:asd1
>>> bool(word) and word[-1].isdigit()
True
>>> word = raw_input("input your alphanumeric word:")
input your alphanumeric word:
>>> bool(word) and word[-1].isdigit()
False
You can look at the last character of the string using slicing [-1], and use the string method isdigit to see if it is a number.
s1 = 'hello world'
s2 = 'hello again3'
>>> s1[-1].isdigit()
False
>>> s2[-1].isdigit()
True
print 'true' if re.search(r'\d$', word) else 'false'
You could also use:
print 'true' if word[-1].isdigit() else 'false'
...but this will throw an IndexError if the word is zero-length.

How to detect lowercase letters in Python?

I need to know if there is a function that detects the lowercase letters in a string. Say I started writing this program:
s = input('Type a word')
Would there be a function that lets me detect a lowercase letter within the string s? Possibly ending up with assigning those letters to a different variable, or just printing the lowercase letters or number of lowercase letters.
While those would be what I would like to do with it I'm most interested in how to detect the presence of lowercase letters. The simplest methods would be welcome.
To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:
for c in s:
if c.islower():
print c
Note that in Python 3 you should use print(c) instead of print c.
Possibly ending up with assigning those letters to a different variable.
To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:
>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']
Or to get a string you can use ''.join with a generator:
>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'
There are 2 different ways you can look for lowercase characters:
Use str.islower() to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:
lowercase = [c for c in s if c.islower()]
You could use a regular expression:
import re
lc = re.compile('[a-z]+')
lowercase = lc.findall(s)
The first method returns a list of individual characters, the second returns a list of character groups:
>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']
There are many methods to this, here are some of them:
Using the predefined str method islower():
>>> c = 'a'
>>> c.islower()
True
Using the ord() function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:
>>> c = 'a'
>>> ord(c) in range(97, 123)
True
Checking if the letter is equal to it's lowercase form:
>>> c = 'a'
>>> c.lower() == c
True
Checking if the letter is in the list ascii_lowercase of the string module:
>>> from string import ascii_lowercase
>>> c = 'a'
>>> c in ascii_lowercase
True
But that may not be all, you can find your own ways if you don't like these ones: D.
Finally, let's start detecting:
d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]
# here i used islower() because it's the shortest and most-reliable
# one (being a predefined function), using this list comprehension
# is (probably) the most efficient way of doing this
You should use raw_input to take a string input. then use islower method of str object.
s = raw_input('Type a word')
l = []
for c in s.strip():
if c.islower():
print c
l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)
Just do -
dir(s)
and you will find islower and other attributes of str
import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper
Prints:
Type a word: A Title of a Book
itleofaook ATB
Or you can use a list comprehension / generator expression:
slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper
Prints:
Type a word: A Title of a Book
itleofaook ATB
If you don't want to use the libraries and want simple answer then the code is given below:
def swap_alpha(test_string):
new_string = ""
for i in test_string:
if i.upper() in test_string:
new_string += i.lower()
elif i.lower():
new_string += i.upper()
else:
return "invalid "
return new_string
user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)

Categories

Resources