To be more specific, it's for an "if" condition
I have a list of strings which have 5 spaces then the last character
Is there a character that can replace the last character of every string
Like:
if string == " &":
do something
And the condition would be true if & == any type of character
You can access the last character by slicing, e.g. -1 is the last one:
lst = ['&', 'A', 'B', 'C']
s = 'some random string which ends on &'
if s[-1] in lst:
print('hurray!')
#hurray!
Alternatively you can also use .endswith() if its only a few entries:
s = 'some random string which ends on &'
if s.endswith('&') or s.endswith('A'):
print('hurray!')
#hurray!
Since you also asked how to replace the last character, this can be done like this:
s = s[:-1] + '!'
#Out[72]: 'some random string which ends on !'
As per you comment, here is a wildcard solution:
import re
s = r' &'
pattern = r' .{1}$'
if re.search(pattern, s):
print('hurray!')
#hurray!
Try this:
if string[-1] == 'A' or string[-1] == '1':
do something
You may use a regular expression along with re.search, for example:
vals = ["validA", "valid1", "invalid"]
for val in vals:
if re.search(r'[A1]$', val):
print(val + ": MATCH")
This prints:
validA: MATCH
valid1: MATCH
Perhaps you're looking for the .endswith() function? For example:
if "waffles".endswith("s"):
...
Related
This question already has answers here:
How to use re to find consecutive, repeated chars
(3 answers)
Closed 2 years ago.
I want to detect if there are three of the same letter next to each other in a string.
For example:
string1 = 'this is oooonly excaple' # ooo
string2 = 'nooo way that he did this' # ooo
string3 = 'I kneeeeeew it!' # eee
Is there any pythonic way to do this?
I guess that a solution like this is not the best one:
for letters in ['aaa', 'bbb', 'ccc', 'ddd', ..., 'zzz']:
if letters in string:
print(True)
you dont have to use regex but solution is little long for something as simple as that
def repeated(string, amount):
current = None
count = 0
for letter in string:
if letter == current:
count += 1
if count == amount:
return True
else:
count = 1
current = letter
return False
print(repeated("helllo", 3) == True)
print(repeated("hello", 3) == False)
You can use groupby to group similar letters and then check the length of each group:
from itertools import groupby
string = "this is ooonly an examplle nooo wway that he did this I kneeeeeew it!"
for letter, group in groupby(string):
if len(list(group)) >= 3:
print(letter)
Will output:
o
o
e
If you don't care for the letters themselves and just want to know if there was a repetition, take advantage of short-circuiting with the built-in any function:
print(any(len(list(group)) >= 3 for letter, group in groupby(string)))
One of the best ways to tackle these simple pattern problems is with regex
import re
test_cases = [
'abc',
'a bbb a', # expected match for 'bbb'
'bb a b',
'aaa c bbb', # expected match for 'aaa' and 'bbb'
]
for string in test_cases:
# We use re.findall because don't want to keep only with the first result.
# In case we want to stop at the first result, we should use re.search
match = re.findall(r'(?P<repeated_characters>(.)\2{2})', string)
if match:
print([groups[0] for groups in match])
Result:
['bbb']
['aaa', 'bbb']
Use a regular expression:
import re
pattern = r"(\w)\1{2}"
string = "this is ooonly an example"
print(re.search(pattern, string) is not None)
Output:
True
>>>
How about using regex? - ([a-z])\1{2}
>>> import re
>>> re.search(r'([a-z])\1{2}', 'I kneeew it!', flags=re.I)
<re.Match object; span=(4, 7), match='eee'>
re.search will return None if it doesn't find a match, otherwise it'll return a match object, you can get the full match from the match object using [0] on it.
string1 = 'nooo way that he did this'
for i in range(0,len(string1)-2):
sub_st = string1[i:i+3]
if sub_st[0]*3 == sub_st:
print('true')
print statement is from your example.
sub_st[0]*3 clone fist character in the sub_st combine those into single string. If original sub_st and clone one same it means sub_st carries the same latter 3 times.
If you don't need a general answer for n repetitions you can just iterate through the string and print true if previous character and next character are equal to current character, excluding the first and last character.
text = "I kneeeeeew it!"
for i in range(1,len(text)-1):
if text[i-1] == text[i] and text[i+1] == text[i]:
print(True)
break;
We can define following predicate with itertools.groupby + any functions like
from itertools import groupby
def has_repeated_letter(string):
return any(len(list(group)) >= 3 for _, group in groupby(string))
and after that use it
>>> has_repeated_letter('this is oooonly example')
True
>>> has_repeated_letter('nooo way that he did this')
True
>>> has_repeated_letter('I kneeeeeew it!')
True
>>> has_repeated_letter('I kneew it!')
False
we get a string from user and want to lowercase it and remove vowels and add a '.' before each letter of it. for example we get 'aBAcAba' and change it to '.b.c.b' . two early things are done but i want some help with third one.
str = input()
str=str.lower()
for i in range(0,len(str)):
str=str.replace('a','')
str=str.replace('e','')
str=str.replace('o','')
str=str.replace('i','')
str=str.replace('u','')
print(str)
for j in range(0,len(str)):
str=str.replace(str[j],('.'+str[j]))
print(str)
A few things:
You should avoid the variable name str because this is used by a builtin, so I've changed it to st
In the first part, no loop is necessary; replace will replace all occurrences of a substring
For the last part, it is probably easiest to loop through the string and build up a new string. Limiting this answer to basic syntax, a simple for loop will work.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
Another potential improvement: for the second part, you can also write a loop (instead of your five separate replace lines):
for c in 'aeiou':
st = st.replace(c, '')
Other possibilities using more advanced techniques:
For the second part, a regular expression could be used:
st = re.sub('[aeiou]', '', st)
For the third part, a generator expression could be used:
st_new = ''.join(f'.{c}' for c in st)
You can use str.join() to place some character in between all the existing characters, and then you can use string concatenation to place it again at the end:
# st = 'bcb'
st = '.' + '.'.join(st)
# '.b.c.b'
As a sidenote, please don't use str as a variable name. It's the name of the "string" datatype, and if you make a variable named it then you can't properly work with other strings any more. string, st, s, etc. are fine, as they're not the reserved keyword str.
z = "aBAcAba"
z = z.lower()
newstring = ''
for i in z:
if not i in 'aeiou':
newstring+='.'
newstring+=i
print(newstring)
Here I have gone step by step, first converting the string to lowercase, then checking if the word is not vowel, then add a dot to our final string then add the word to our final string.
You could try splitting the string into an array and then build a new string with the indexes of the array appending an "."
not too efficient but will work.
thanks to all of you especially allani. the bellow code worked.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
This does everything.
import re
data = 'KujhKyjiubBMNBHJGJhbvgqsauijuetystareFGcvb'
matches = re.compile('[^aeiou]', re.I).finditer(data)
final = f".{'.'.join([m.group().lower() for m in matches])}"
print(final)
#.k.j.h.k.y.j.b.b.m.n.b.h.j.g.j.h.b.v.g.q.s.j.t.y.s.t.r.f.g.c.v.b
s = input()
s = s.lower()
for i in s:
for x in ['a','e','i','o','u']:
if i == x:
s = s.replace(i,'')
new_s = ''
for i in s:
new_s += '.'+ i
print(new_s)
def add_dots(n):
return ".".join(n)
print(add_dots("test"))
def remove_dots(a):
return a.replace(".", "")
print(remove_dots("t.e.s.t"))
I need to replace all occurrences of dots but only if the dot is in parenteses, with something else (semicolon for example), using python like this:
Input: "Hello (This . will be replaced, this one. too)."
Output:"Hello (This ; will be replaced, this one; too)."
Assuming the parentheses are balanced and not nested, here's an idea with re.split.
>>> import re
>>>
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...: for m in re.split('(\([^)]+\))', s))
...:
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'
The main trick here is to wrap the regex \([^)]+\) with another pair of () such that the splitting-matches are kept.
Loop over characters in string, track number of opening and closing parentheses, only replace if more opening than closing parentheses encountered.
def replace_inside_parentheses(string, find_string, replace_string):
bracket_count = 0
return_string = ""
for a in string:
if a == "(":
bracket_count += 1
elif a == ")":
bracket_count -= 1
if bracket_count > 0:
return_string += a.replace(find_string, replace_string)
else:
return_string += a
return return_string
my_str = "Hello (This . will be replaced, this one. too, (even this one . inside nested parentheses!))."
print(my_str)
print(replace_inside_parentheses(my_str, ".", ";"))
Not the most elegant way, but this should work.
def sanitize(string):
string = string.split("(",1)
string0 = str(string[0])+"("
string1 = str(string[1]).split(")",1)
ending = str(")"+string1[1])
middle = str(string1[0])
# replace second "" with character you'd like to replace with
# I.E. middle.replace(".","!")
middle = middle.replace(".","").replace(";","")
stringBackTogether = string0+middle+ending
return stringBackTogether
a = sanitize("Hello (This . will be replaced, this one. too).")
print(a)
I would like to detect brackets in a string, and if found, remove the brackets and all data in the brackets
e.g.
Developer (12)
would become
Developer
Edit: Note that the string will be a different length/text each time, and the brackets will not always be present.
I can detect the brackets using something like
if '(' in mystring:
print 'found it'
but how would I remove the (12)?
You can user regex and replace it:
>>> re.sub(r'\(.*?\)', '','Developer (12)')
'Developer '
>>> a='DEf (asd () . as ( as ssdd (12334))'
>>> re.sub(r'\(.*?\)', '','DEf (asd () . as ( as ssdd (12334))')
'DEf . as )'
I believe you want something like this
import re
a = "developer (12)"
print(re.sub("\(.*\)", "", a))
Since it's always at the end and there is no nested brackets:
s = "Developer (12)"
s[:s.index('(')] # or s.index(' (') if you want to get rid of the previous space too
For nested brackets and multiple pairs in string this solution would work
def replace_parenthesis_with_empty_str(str):
new_str = ""
stack = []
in_bracker = False
for c in str :
if c == '(' :
stack.append(c)
in_bracker = True
continue
else:
if in_bracker == True:
if c == ')' :
stack.pop()
if not len(stack):
in_bracker = False
else :
new_str += c
return new_str
a = "fsdf(ds fOsf(fs)sdfs f(sdfsd)sd fsdf)c sdsds (sdsd)"
print(replace_parenthesis_with_empty_str(a))
I have a string s with nested brackets: s = "AX(p>q)&E((-p)Ur)"
I want to remove all characters between all pairs of brackets and store in a new string like this: new_string = AX&E
i tried doing this:
p = re.compile("\(.*?\)", re.DOTALL)
new_string = p.sub("", s)
It gives output: AX&EUr)
Is there any way to correct this, rather than iterating each element in the string?
Another simple option is removing the innermost parentheses at every stage, until there are no more parentheses:
p = re.compile("\([^()]*\)")
count = 1
while count:
s, count = p.subn("", s)
Working example: http://ideone.com/WicDK
You can just use string manipulation without regular expression
>>> s = "AX(p>q)&E(qUr)"
>>> [ i.split("(")[0] for i in s.split(")") ]
['AX', '&E', '']
I leave it to you to join the strings up.
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> re.compile("""\([^\)]*\)""").sub('', s)
'AX&E'
Yeah, it should be:
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> p = re.compile("\(.*?\)", re.DOTALL)
>>> new_string = p.sub("", s)
>>> new_string
'AX&E'
Nested brackets (or tags, ...) are something that are not possible to handle in a general way using regex. See http://www.amazon.de/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1?ie=UTF8&s=gateway&qid=1304230523&sr=8-1-spell for details why. You would need a real parser.
It's possible to construct a regex which can handle two levels of nesting, but they are already ugly, three levels will already be quite long. And you don't want to think about four levels. ;-)
You can use PyParsing to parse the string:
from pyparsing import nestedExpr
import sys
s = "AX(p>q)&E((-p)Ur)"
expr = nestedExpr('(', ')')
result = expr.parseString('(' + s + ')').asList()[0]
s = ''.join(filter(lambda x: isinstance(x, str), result))
print(s)
Most code is from: How can a recursive regexp be implemented in python?
You could use re.subn():
import re
s = 'AX(p>q)&E((-p)Ur)'
while True:
s, n = re.subn(r'\([^)(]*\)', '', s)
if n == 0:
break
print(s)
Output
AX&E
this is just how you do it:
# strings
# double and single quotes use in Python
"hey there! welcome to CIP"
'hey there! welcome to CIP'
"you'll understand python"
'i said, "python is awesome!"'
'i can\'t live without python'
# use of 'r' before string
print(r"\new code", "\n")
first = "code in"
last = "python"
first + last #concatenation
# slicing of strings
user = "code in python!"
print(user)
print(user[5]) # print an element
print(user[-3]) # print an element from rear end
print(user[2:6]) # slicing the string
print(user[:6])
print(user[2:])
print(len(user)) # length of the string
print(user.upper()) # convert to uppercase
print(user.lstrip())
print(user.rstrip())
print(max(user)) # max alphabet from user string
print(min(user)) # min alphabet from user string
print(user.join([1,2,3,4]))
input()