Python: Why dosent this work? [closed] - python

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:]

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

Get the indices of capital letters in a string [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 8 years ago.
Improve this question
Say for example I have the following string:
Hello
And my job is to shift all the letters over by however many spots I am told to, and lets say it is 1, so the result would be:
elloH
But my program returns it as
elloh
What I want to know is, how can I get a list with the indices of where a capital letter is, so I can make the letters at that same spot in the new string uppercase?
I think you would do it by converting the String to a list through list(string) and then iterate through the list so, and whenever the item in the list returns true for isUpper(), then store the index of that in a list. I just am not able to write it in python.
I will assume that your question is regarding:
And my job is to shift all the letters over by however many spots I am told to
In that case, try:
def shift(s, n):
return s[n:] + s[:n]
Examples:
>>> shift('Hello', 1)
'elloH'
>>> shift('Hello', 2)
'lloHe'
This appears to be the output that you were looking for.
How to get indices of the capital letters in a string:
def getindices(s):
return [i for i, c in enumerate(s) if c.isupper()]
Examples:
>>> getindices('Hello')
[0]
>>> getindices('HeLlO')
[0, 2, 4]
To add to the solution by #John1024
This supports any number to rotate by
def shift(s, n):
return s[n%len(s):] + text[:n%len(s)]
>>> shift('Hello', 51)
'elloH'

is there any strncpy() equivalent function in python? [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
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

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