This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 6 years ago.
if I have a str and the I use str.index(char) and the char does not exist, is it possible with one line to assign another char to the variable?
Maybe like this
str = "bar/foo"
t = str.index("_") | "Empty"
str dosen't contain _ , so the string "Empty" should be assigned instead.
Since str.index() would throw a ValueError if substring is not in a string, wrap it into an if/else checking the presence of substring in a string via in operator:
>>> s = "bar/foo"
>>> s.index("_") if "_" in s else "Empty"
"Empty"
>>> s = "bar_foo"
>>> s.index("_") if "_" in s else "Empty"
3
Related
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 months ago.
So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.
This is probably a lot more simple than what I'm doing, but this is what I've been attempting to do (and failing miserably at)
for j in range(2, len(string)-1):
char = string[j]
plus = string[j+1]
minus = string[j-1]
if char == plus or char == minus:
string.replace(char, "")
For reference, the code SHOULD act as:
input: ppmpvvpmmp
output: pmpvmp
But instead, the output does not change at all.
Again, I'm aware that this is most likely very easy and I'm overcomplicating, but I'm genuinely struggling here and have tried a lot of similar variations
I would use a regular expression replacement here:
inp = "ppmpvvpmmp"
output = re.sub(r'(\w)\1', r'\1', inp)
print(output) # pmpvpmp
The above assumes that a duplicate is limited to a single pair of same letters. If instead you want to reduce 3 or more, then use:
inp = "ppmpvvvvvpmmmp"
output = re.sub(r'(\w)\1+', r'\1', inp)
print(output) # pmpvpmp
This question already has answers here:
How to check a string for a special character?
(5 answers)
Closed 3 years ago.
The prog asks me to check whether any special char like !##... are present in the given string. How can I do this?
Define a function first. Use re.search with a pattern [^\w\s\d] which will match anything that is not a letter, space, digit, or underscore.
In [43]: def foo(string):
...: return 'Valid' if not re.search('[^\w\s]', string) else 'Invalid'
...:
Now, you may call it with your strings:
In [44]: foo("##example!")
Out[44]: 'Invalid'
In [45]: foo("Seemingly valid string")
Out[45]: 'Valid'
Try this any(x in string for x in '##!')
You can use re.match to do this task.
Try :
word = "##example!"
import re
print ("Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid")
Output :
Invalid
This question already has answers here:
Remove specific characters from a string in Python
(26 answers)
Removing numbers from string [closed]
(8 answers)
Closed 8 years ago.
I’d like to eliminate numbers in a string in Python.
str = "aaaa22222111111kkkkk"
I want this to be "aaaakkkkk".
I use re.sub to replace, but it doesn't work:
str = "aaaa22222111111kkkkk"
str = re.sub(r'^[0-9]+$',"",str)
Maybe, this replaces a string which only contains numbers with "".
How should I do with this?
your regex is wrong:
re.sub(r'[0-9]',"",str)
should work:
>>> str="aaaa22222111111kkkkk"
>>> re.sub(r'[0-9]',"",str)
'aaaakkkkk'
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 8 years ago.
I'm trying to remove a set of characters from a larger string. Here's what I've tried:
string = 'aabc'
remove = 'ac'
for i in remove:
string.replace(i, '', 1)
print(string)
I keep getting back my original string when I run this. The variable i is getting the characters 'a' and then 'c'. The replace function works for me if i do string.replace('a', '', 1). Why isn't this working or is there a simpler way to do this?
Strings are immutable in python, so string.replace() does not mutate the string; it returns a new string with the replacements.
Try this:
string = string.replace(i, '', 1)
replace returns a new string.
Strings in python are immutable.
As such, you must assign the return value:
string_new = "ABCD".replace("A","Z")
A new string will be generated as Strings are immutable...
Try this -
string = 'aabc'
remove = 'ac'
for i in remove:
result = string.replace(i, '', 1)
print(result)
As Strings are immutable you cant use replace with just string.replace().
As a better way use set :
>>> s='aabcc'
>>> s=''.join(set(s))
'acb'
This question already has answers here:
How to make Regex choose words separately
(2 answers)
Closed 8 years ago.
In Python
How can I make re.findall('a.*c', 'abcbc') match abc instead of abcbc.
Use 'non-greedy' matchers:
>>> re.findall('a.*?c', 'abcbc')
['abc']
As
>>> re.findall('a.*?c','abbbc')
>>> ['abbbc']
I am not sure whether that's you want.
If you just need 'abc' (only one letter in middle, instead of only one type of letter in middle), it's better to use:
>>> re.findall('a.?c','abbbc')
>>> []
"." means any letter, "" means any length and "?" means one or zero, "." may be calculated before apply "?", so it depends on your need for which case to use.