How to add a integer to a string? - python

So I got this
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome.

Here are possible options:
Use %s
itemIdsCount = 'itemIds%s' + count
Cast integer to string first
itemIdsCount = 'itemIds' + str(count)
Use .format() method
itemIdsCount = 'itemIds{}'.format(count)
If you have python 3.6, you can use F-string (Literal String Interpolation)
count = 1
itemIdsCount = f'itemIds{count}'

You can use format, i.e.:
count2 = 1
itemIdsCount = ('itemIds{}'.format(count2))
while (count2 < 2):
#Do stuff
count2 += 1 # it's simpler like this

The following will create the string you need:
itemIdsCount = "itemIds%d" % count2
so you can look up python for strings, and see how you can use %s,%d and others to inject what comes after.
As an additionalNote, if you need to append multiple items you would need to say something like this:
itemIdsCount = "Id:%d Name:%s" % (15, "Misha")

if you need to equal string and integer maybe you should use str(x) or int(x). in this case itemIdsCount = ('itemIds' + str(count2))

Related

How can I find how many times a string appears in a text with Regex that allows character skipping

I need to explain a little: I want to find how many "abab" exists in "ababab" string.
But skipping is valid like
[abab]ab
[aba]ba[b]
[ab]ab[ab]
[a]ba[bab]
these are all valid, my attempt was to use < /\w*?a\w*?b\w*?a\w*?b/g > which of course did not work. What should I do?
Python solutions are also good for me, I thought regex would be good for this.
Edit:
Marked similar question is quite different to my question
For the little testing I have done, this works:
def abab(to_check):
return is_a(0, to_check)
def is_a(i, to_check):
count = 0
for index, c in enumerate(to_check):
if c == 'a':
count = count + is_b(i + 1, to_check[index + 1:])
return count
def is_b(i, to_check):
count = 0
for index, c in enumerate(to_check):
if c == 'b':
if i == 2:
count = count + 1
else:
count = count + is_a(i, to_check[index + 1:])
return count
print(abab("ababab"))

How can I increment the numerical part of a string?

I have a string like this:
location = "IP.Location.1"
and there are other locations like IP.Location.2, IP.Location.3, etc.
How can I increment the location from IP.Location.2 to IP.Location.3? I always need to increment the numerical part by 1.
Several ways to achieve this but this would be an easy way if you are pre Python 3.6:
for i in range(1, 11):
print('IP.Location.{my_number}'.format(my_number=i))
If you have Python 3.6+ then:
for i in range(1, 11):
print(f'IP.Location.{i}')
Finally if you just have the string and you want to increment up from it then extract the int from the string, extract just the non-int bit and use that as your string and range:
location = "IP.Location.1"
initial_number = int(''.join(filter(str.isdigit, location)))
string_phrase = ''.join([i for i in location if not i.isdigit()])
for i in range(initial_number, initial_number + 10):
print(f'{string_phrase}{i}')
Here is a Python 3.6 + solution:
for i in range(10):
print(f'IP.Location.{i + 1}')
Here’s a generic solution that does exactly what you asked for, i.e. incrementing an integer number at the end of a string that is separated by a dot.
location = "IP.Location.1"
parts = location.rsplit(".", 1)
parts[1] = str(int(parts[1]) + 1)
location = ".".join(parts)
print (location)
# --> IP.location.2
Have you tried adding the strings? See code below.
# create base string
location = "IP.Location."
# introduce counting variable
count = 1
# create empty list to store results
ip_locs = []
# loop to get incremented strings
for i in range(10):
ip_loc = location + str(count)
ip_locs.append(ip_loc)
count = count+1
print(ip_locs)

i+ =1 generating a Syntax error in for loop

eg.
name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
print( name[i], '\t', name[n])
i+ = 1
I remove the i+ = 1 which generates a semantic error. I'm a beginner and am using the python tutorial provided by the python website. Basically I'm practicing forward and backward indexing.
name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
print( name[i], '\t', name[n])
i+ = 1
I'm expecting it to run an output of the name forward then backwards
Your error lies in your i+ = 1 statement, which should be i += 1
Try this:
name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
print( name[i], '\t', name[n])
i += 1
There should be no blank space between the + and =.
i += 1
You can not arbitrarily spread spaces through your code. Certain tokens that Python recognizes have to be written exactly as they are documented. This is true for e.g. class that you can't write cl a ss, and it's also true for what you are using here wich is called an operator. It needs to be written +=, the same way == can't have a space in it etc.
As other commenters have already pointed out, the += is used as a += b and not a+ = b, which the case you have when you do i+ = 1
For simplicity, and since you say you are a beginner, might I suggest using i = i+1 instead.
In addition, you can also simplify your for loop by using length attribute to calculate the index from the end of the string. range(length) is the same as doing range(0,length,1)
name = 'python'
length = len(name)
i = 0
for i in range(length):
print(name[i], '\t', name[length-i-1])
i += 1
The output will be
p n
y o
t h
h t
o y
n p
avoid space between + and =
use i+=1 instead i+ =1
refer here: Behaviour of increment and decrement operators in Python

How to get portion of string from 2 different strings and concat?

I have 2 strings a and b with - as delimiter, want to get 3rd string by concatenating the substring upto last % from a (which is one-two-three-%whatever% in below example) and from string b, drop the substring upto number of dashes found in resultant string (which is 4 in below e.g., that gives bar-bazz), I did this so far, is there a better way?
>>> a='one-two-three-%whatever%-foo-bar'
>>> b='1one-2two-3three-4four-bar-bazz'
>>> k="%".join(a.split('%')[:-1]) + '%-'
>>> k
'one-two-three-%whatever%-'
>>> k.count('-')
4
>>> y=b.split("-",k.count('-'))[-1]
>>> y
'bar-bazz'
>>> k+y
'one-two-three-%whatever%-bar-bazz'
>>>
An alternative approach using Regex:
import re
a = 'one-two-three-%whatever%-foo-bar'
b = '1one-2two-3three-4four-bar-bazz'
part1 = re.findall(r".*%-",a)[0] # one-two-three-%whatever%-
num = part1.count("-") # 4
part2 = re.findall(r"\w+",b) # ['1one', '2two', '3three', '4four', 'bar', 'bazz']
part2 = '-'.join(part2[num:]) # bar-bazz
print(part1+part2) # one-two-three-%whatever%-bar-bazz
For the first substring obtained from a, you can use rsplit():
k = a.rsplit('%', 1)[0] + '%-'
The rest look good to me
Maybe a little shorter ?
a = 'one-two-three-%whatever%-foo-bar'
b = '1one-2two-3three-4four-bar-bazz'
def merge (a,b):
res = a[:a.rfind ('%')+1]+'-'
return (res + "-".join (b.split ("-")[res.count ('-'):]))
print (merge (a,b) == 'one-two-three-%whatever%-bar-bazz')
I personally get nervous when I need to manually increment indexes or concatenate bare strings.
This answer is pretty similar to hingev's, just without the additional concat/addition operators.
t = "-"
ix = list(reversed(a)).index("%")
t.join([s] + b.split(t)[len(a[:-ix].split(t)):])
yet another possible answer:
def custom_merge(a, b):
result = []
idx = 0
for x in itertools.zip_longest(a.split('-'), b.split('-')):
result.append(x[idx])
if x[0][0] == '%' == x[0][-1]:
idx = 1
return "-".join(result)
Your question is specific enough that you might be optimizing the wrong thing (a smaller piece of a bigger problem). That being said, one way that feels easier to follow, and avoids some of the repeated linear traversals (splits and joins and counts) would be this:
def funky_percent_join(a, b):
split_a = a.split('-')
split_b = b.split('-')
breakpoint = 0 # len(split_a) if all of a should be used on no %
for neg, segment in enumerate(reversed(split_a)):
if '%' in segment:
breakpoint = len(split_a) - neg
break
return '-'.join(split_a[:breakpoint] + split_b[breakpoint:])
and then
>>> funky_percent_join('one-two-three-%whatever%-foo-bar', '1one-2two-3three-4four-bar-bazz')
'one-two-three-%whatever%-bar-bazz'
print(f"one-two-three-%{''.join(a.split('%')[1])}%")
that would work for the first, and then you could do the same for the second, and when you're ready to concat, you can do:
part1 = str(f"one-two-three-%{''.join(a.split('%')[1])}%")
part2 = str(f"-{''.join(b.split('-')[-2])}-{''.join(b.split('-')[-1])}")
result = part1+part2
this way it'll grab whatever you set the a/b variables to, provided they follow the same format.
but then again, why not do something like:
result = str(a[:-8] + b[22:])

formatting list to convert into string

Here is my question
count += 1
num = 0
num = num + 1
obs = obs_%d%(count)
mag = mag_%d%(count)
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
print index
The above code gives the following results
obs1 = mag1
obs2 = mag2
obs3 = mag3
and so on.
obsforrbd = parentV = {0},format(index)
cmds.dynExpression(nPartilce1,s = obsforrbd,c = 1)
However when i run the code above it only gives me
parentV = obs3 = mag3
not the whole list,it only gives me the last element of the list why is that..??
Thanks.
I'm having difficulty interpreting your question, so I'm just going to base this on the question title.
Let's say you have a list of items (they could be anything, numbers, strings, characters, etc)
myList = [1,2,3,4,"abcd"]
If you do something like:
for i in myList:
print(i)
you will get:
1
2
3
4
"abcd"
If you want to convert this to a string:
myString = ' '.join(myList)
should have:
print(myString)
>"1 2 3 4 abcd"
Now for some explanation:
' ' is a string in python, and strings have certain methods associated with them (functions that can be applied to strings). In this instance, we're calling the .join() method. This method takes a list as an argument, and extracts each element of the list, converts it to a string representation and 'joins' it based on ' ' as a separator. If you wanted a comma separated list representation, just replace ' ' with ','.
I think your indentations wrong ... it should be
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
but Im not sure if thats your problem or not
the reason it did not work before is
while num < 4:
obsforsim = obs + mag
#does all loops before here
mylist.append(obsforsim) #appends only last
The usual pythonic way to spit out a list of numbered items would be either the range function:
results = []
for item in range(1, 4):
results.append("obs%i = mag_%i" % (item, item))
> ['obs1 = mag_1', 'obs2 = mag_2', 'ob3= mag_3']
and so on (note in this example you have to pass in the item variable twice to get it to register twice.
If that's to be formatted into something like an expression you could use
'\n'.join(results)
as in the other example to create a single string with the obs = mag pairs on their own lines.
Finally, you can do all that in one line with a list comprehension.
'\n'.join([ "obs%i = mag_%i" % (item, item) for item in range (1, 4)])
As other people have pointed out, while loops are dangerous - its easier to use range

Categories