is there any strncpy() equivalent function in python? [closed] - python

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

Related

How to find the first character that repeats in a string? [closed]

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

How to get the value from a variable for the below scenario ? [Python] [closed]

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
my_str = 'I am want you'
l = ['my_str']
for value in l:
print value
I would like to fetch the value stored in my_str.
Expected output
I am want you
You can use eval.Otherwise use dictionary is good approach
my_string = 'I am want you'
l = ['my_string']
for value in l:
print eval(value)
#output
I am want you
"eval" seems a better solution, but "exec" is also feasible.
>>> my_string = 'hello world'
>>> l = ['my_string']
>>> for each in l:
... exec 'print ' + each
... exec 'a = ' + each
... print 'a = %s' % a
...
hello world
a = hello world
I also agree that it is an bad idea to use eval/exec for this purpose. Using dictionary might be a better way.
I am not 100% sure what your intention is. But if you want to get integer values from a string in python there are some solutions.
>>> import re
>>> string1 = "498results should get"
>>> map(int, re.findall(r'\d+', string1))
[498]
Solution from jamylak
This groups all numbers with the help of a regular expression and then maps them, thus inserting them into an array.
You then just could iterate over this array
>>> arr = map(int, re.findall(r'\d+', string1))
>>> for num in arr:
>>> print num
498
Edit: Yeah, seems like I misunderstood your question

Change part of string into * [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
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!

Python: Why dosent this work? [closed]

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 8 years ago.
Improve this question
So i have this small piece of code which just wont work:
while c<b:
str2 += str1[c]
c+=1
print str2
b is the length of str1 that i want to copy to str2, and c is the point which i want to begin transfer from str1, then the while loop is just supposed to transfer all the characters from str1 to str2.
For some reason i can't seem to print str2 and get this error message:
"NameError: name 'str2' is not defined"
My guess is that I'm just doing something simple wrong, I just began experimenting with Python and have only really done C# before.
A better approach would be to slice the strings:
str2 = str1[c:b]
This copies str1 from character number c and up to character number b into str2.
For example:
>>> 'Hello World'[3:7]
'lo W'
Here's a little information about Python's slice notation: Explain Python's slice notation
You have to initialize str2:
str2 = ''
while c<b:
str2 += str1[c]
c+=1
print str2
Or else do a function that receives str2 as parameter:
def myfunc(str2=''):
while c<b:
str2 += str1[c]
c+=1
return str2
where str2 parameter is by default initialized as '', i.e. empty string.
With
str2 += str1[c]
You are saying, "please add str1[c]" to whatever is already in str2 .. the problem is that you haven't initialized str2 with anything (at least in the code you show).
Easiest fix is to give str2 an initial value before you use it in the loop, e.g., str2=''
Why not to use something in the lines of:
str2 = str1[c:]

how can I tell if two strings have a common character section?--Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
there are two strings:
str1 = "black_red_yellow"
str2 = "blue_red_green"
which python library can I use to check these two strings have a substring"_red_" in common? thank you in advance.
Something like this should work if you don't know the actual string you're searching for
import difflib
str1 = "black_red_yellow"
str2 = "blue_red_green"
difference = difflib.SequenceMatcher()
difference.set_seqs(str1, str2)
for match in difference.get_matching_blocks():
print str1[match[0]:match[0] + match[2]]
test for presence of common substring, including length 1:
if set(str1).intersection(set(str2)): print "yes we can!"
if you can't find anything else, then there's at least this naive implementation:
str1 = "black_red_yellow"
str2 = "blue_red_green"
if len(str1) < len(str2):
min_str = str1
max_str = str2
else:
min_str = str2
max_str = str1
matches = []
min_len = len(min_str)
for b in xrange(min_len):
for e in xrange(min_len, b, -1):
chunk = min_str[b:e]
if chunk in max_str:
matches.append(chunk)
print max(matches, key=len)
prints _red_
You can use difflib to compare strings in that way. However, if you know the string you're looking for you could just do '_red_' in str1 and '_red_' in str2. If you don't know the string, then do you look for a specific length of match? E.g. would 'red' match 'blue' because they both contain 'e'? The shortest, simplest way of checking for any match at all would be
bool([a for a in str1 if a in str2])
Edit: Or, more efficiently,
any(a for a in str1 if a in str2)

Categories

Resources