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
Let's say I have an IBAN: NL20INGB0001234567
How can I change all digits except the last 4 into *:
Input: NL20INGB0001234567
Output: NL20INGB******4567
all digits but NL*20*
Using regex:
>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'
Simplest?
import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)
Result:
'NL20INGB****4567'
tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
if i.isdigit():
tmp += '*'
else:
tmp += i
iban = iban[:4] + tmp + iban[-4:]
>>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'
s = "IBAN: NL20INGB0001234567"
s = [ele for ele in s.split(':')[-1] if ele.strip()]
mask = [1 for ele in range(len(s) - 10)] + [0] * 6 + [1] * 4
print ''.join(["*" if mask[i] == 0 else ele for i, ele in enumerate(s)])
Output:
NL20INGB******4567
Based on the way you worded the question, I'm assuming you want to format an IBAN string from
##################
to
########******####
Based on this, a simple solution is to write this function:
def ConverterFunction(IBAN):
return IBAN[:8]+"******"+IBAN[14:]
and call it with this line:
ConverterFunction(<your IBAN here>)
Of course, attaching assignments or prints where necessary.
EDIT: A bit of an explanation might be necessary, too.
Whatever you are using as IBAN is a string, and strings can be sliced. By slicing, a person can pick up parts of a string and leave others behind. It uses the index of each letter's position, like so:
This is OK
0123456789
Note, the index always starts at 0, not 1.
Example of taking string slices:
examplestring = "EXAMPLE!"
print examplestring[:3] # "[:3]" means "from beginning to position 3"
print examplestring[5:] # "[5:]" means "from position 5 to end of string"
print examplestring[3:5] # "[3:5]" means "from position 3 to position 5"
Output:
>> EXAM
>> LE!
>> MPL
So in my solution, what the function ConverterFunction(IBAN) does is:
#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle
Understand?
Happy coding!
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
For example, if the string is pyeneapple then the answer should be p since p is the first element that is present again in the string (and not e).
Can someone help with the Python code for this?
Here is my attempt:
thestring = "pyeneapple"
list_a = []
list_b = []
for i in thestring:
if i in list_a:
list_b.append(i)
else:
list_a.append(i)
print(list_b[0])
The problem is that this code prints e as the answer instead of p.
You can replace comparing characters from string and then compare it to the string.
s = "pyeneapple"
a = []
for i in s:
if i in s.replace(i, "", 1):
a.append(i)
print(a[0])
Output: p
Use a character counter to make it easier to implement and improve readability.
from collections import Counter
counts = Counter(s)
for i in s:
if counts[i]>1:
print(i)
break
You can use the built-in function enumerate():
for i, c in enumerate(thestring):
if thestring[:i+1].count(c) > 1:
print(c)
break
As there is a split point of view in the comment, I'm writing about the code giving the first element that repeats itself again in the behind strings.
thestring = "supercalifragi"
for i in range(len(thestring)):
if thestring[i] in thestring[i+1:]:
element = thestring[i]
break
element
Out[10]: 'r'
i would try with the buid-in count function for the list-type like this :
t = "pyeneapple"
for i in list(t):
if t.count(i)>0:
print(i)
break
>>> p
You could find the first location using re.search where the string matches 2 of the same characters using a capture group and a backreference
import re
m = re.search(r"(.)\1", "pyeneapple")
if m:
print(m.group(1))
Output
p
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to change 'a,b,c,d,e,f,g,e' to 'a,b#c,d#e,f#g,e'.
Input:
'a,b,c,d,e,f,g,e'
Output:
'a,b#c,d#e,f#g,e'
Is it possible?
For the regex lovers:
import re
input = 'a,b,c,d,e,f,g,e'
output = re.sub(r',([^,]*),', r',\1#', input)
You can try this, though its a little complex:
a = 'a,b,c,d,e,f,g,e'
l = a.split(',')
res=''.join([i+',' if num%2==0 else i+'#' for num,i in enumerate(l)]).strip('#').strip(',')
Yes it is possible, here is another method that just involves creating a new string and changing what gets added depending on the condition.
def func(s):
res = ''
i = 0
for c in s:
if c == ',':
i += 1
res += '#' if c == ',' and i % 2 == 0 else c
return res
>>> a = 'a,b,c,d,e,f,g,e'
>>> func(a)
'a,b#c,d#e,f#g,e'
try this-
>>> a = 'a,b,c,d,e,f,g,e'
>>> z=','.join([val if (idx)%2!=0 else '#'+val for idx,val in enumerate(a.split(','))]).replace('#','',1).replace(',#','#')
>>> print z
>>> a,b#c,d#e,f#g,e
You can use stepped slicing, zip, and str.join to achieve this pretty readily.
a = 'a,b,c,d,e,f,g,e'
pairs = zip(a.split(',')[::2], a.split(',')[1::2])
print '#'.join(','.join(p) for p in pairs)
# a,b#c,d#e,f#g,e
This assumes that there are an odd number of commas and the "pairs" are meant to be demarcated by # (as noted in the comment).
a = 'a,b,c,d,e,f,g,e'
b = a.split(',')
it = iter(b[ 1: -1])
result = []
while True:
try:
result.append("{0}#{1}".format(next(it), next(it)))
except StopIteration:
break
print(",".join([b[0]] + result + [b[-1]]))
Output:
a,b#c,d#e,f#g,e
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?
There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.
The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length
You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.
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 need help on how to define and test three functions on strings. Following these guidelines. This is review for my exam on Wednesday and would really like to have the correct solutions because mine are all coming back with the syntax errors.
I need to come up with the code for all three examples following the requirements listed below.
Without using any string methods only len function and the string operations +, *, indexing slicing, and == for comparing strings or characters.
In the repl function, use the accumulator pattern to build up the new string.
Examples
The ends function takes a string as argument; if the string has two or more characters, it returns a string consisting of the first and last character of the given string; otherwise, it returns the given string.
>>> ends("ab")
'ab'
>>> ends("abc")
'ac'
>>> ends("a long sentence")
'ae'
>>> ends("")
''
>>> ends("*")
'*'
The butends function takes a string argument; if the string has two or more characters, it returns a string consisting of all but the first and last character of the string; otherwise, it returns the given string.
>>> butends("abcde")
'bcd'
>>> butends("abc")
'b'
>>> butends("a long sentence")
' long sentenc'
>>> butends("")
''
>>> butends("a")
'a'
The repl function takes three arguments:
old is a single character;
new is a string of 0 or more characters;
s is any string.
I know that it returns a new string formed by replacing every occurrence of old in s with new.
>>> repl('a', 'A', 'fast faces react snappily')
'fAst fAces reAct snAppily'
>>> repl('*', '+++', 'a*b = c*d')
'a+++b = c+++d'
>>> repl(' ', '\n', 'Practice every day.')
'Practice\nevery\nday.'
>>> print(repl(' ', '\n', 'Practice every day.'))
Practice
every
day.
>>> repl(",", ":", "a,b,cde,fghi")
'a:b:cde:fghi'
what I have so far for part 3 is:
def repl(old, new, s):
newStr = ""
for ch in s:
if ch != old:
newStr = newStr + ch
else:
newStr = newStr + new
return newStr
The code listed above does not replace the correct characters I'm not sure where I went wrong.
Here is one possible solution for the three functions. Note that, as I mentioned above in the comments, you would learn a lot more if you would show us what you have tried and what the problems with it are.
def ends (s):
if len(s) > 2:
return s[0] + s[-1]
else:
return s
def butends (s):
if len(s) > 2:
return s[1:-1]
else:
return s
def repl (find, replacement, s):
newString = ''
for c in s:
if c == find:
newString += replacement
else:
newString += c
return newString
If you can use len() and slicing, it would be best to simply grab
the first and last characters and return that.
def ends(input):
if len(input) < 2:
return input
else:
return input[0] + input[-1]
You can pretty much do the same thing here:
def butends(input):
if len(input) < 2:
return input
else:
return input[1:-1]
For this one, there's a function in Python called replace, but I'm
not sure you can use it.
def repl(old, new, input):
return input.replace(old, new)
If you can't, then simply loop through the input and replace each character whenever it matches with new.
I like programming assignments:
def ends (s): return s [0] + s [-1] if len (s) > 1 else s
def butends (s): return s [1:-1] if len (s) > 1 else s
def repl (a, b, c, acc = ''): return acc if not c else repl (a, b, c [1:], acc + (b if c [0] == a else c [0] ) )
Not sure what an "accumulator pattern" is, so for the replacement I used a recursive function with an accumulator as known from functional programming.
1)
def ends(s):
if len(s)<=2: return s
return s[0]+s[-1]
2)
def butends(s):
if len(s)<=2: return s
return s[1:-1]
3)
def repl(s,old,new):
return s.replace(old,new)
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
is there any equivalent function for strncpy() of C in python?
I want to replace 6 characters in the second string from the first string.
'wonderful' should be replaced with 'beautiful'. The following is the code in C.
str1 = "wonderful";
str2 = "beautiful";
strncpy(str2,str1,6);
I want to do this in python.
Thanks in advance.
I want to replace 6 characters in the second string from the first string
str2 = str1[:6] + str2[6:]
You don't copy strings in python as they're immutable. You simply reassign them like this:
str2 = str1[:6] + str2[6:]
you also have your destination and source strings mixed up.
Python strings are immutable, so you cannot modify them like you do in other languages. You have to create a new string and reassign str2:
str2 = str1[:6] + str2[6:]
You can use bytearray if you want in-place modification(normal strings are immutable):
>>> str1 = bytearray("wonderful")
>>> str2 = bytearray("beautiful")
for i in xrange(6):
str2[i] = str1[i]
...
>>> print str2
wonderful
Function:
def strncpy(a, b, ind1, ind2):
for i in xrange(ind1-1, ind2):
a[i] = b[i]
...
>>> str1 = bytearray("wonderful")
>>> str2 = bytearray("beautiful")
>>> strncpy(str2, str1, 1, 6)
>>> print str2
wonderful