How can I increment the numerical part of a string? - python

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)

Related

How to add space in between set amount of characters in Python?

I have a list of phone numbers and these need to be written in a certain way.
As for now they're listed as "+3212345678" and I wish the add spaces in between characters after certain amounts of numbers.
Result should be "+32 1 234 56 78"
You can use the format method with unpacking to provide it with each individual character as arguments. This will let you control the separators and get fancy formatting capabilities:
sep = "({}{}{}) {} {}{}{}.{}{}.{}{}" # {} are placeholders for digits
t = "+3212345678"
f = sep.format(*t)
print(f)
(+32) 1 234.56.78
You could extend this to using a dictionary for different formats depending on the length of the phone number (or other attributes):
seps = { 6:"{}{}.{}{}.{}{}",
7:"{}{}{}.{}{}.{}{}",
8:"{}{} {}{}.{}{}.{}{}",
10:"({}{}) {} {}{}{}.{}{}.{}{}",
11:"({}{}{}) {} {}{}{}.{}{}.{}{}" }
t = "+3212345678"
f = seps[len(t)].format(*t)
print(f)
"(+32) 1 234.56.78"
t = "44345678"
f = seps[len(t)].format(*t)
print(f)
"44 34.56.78"
Try the following in python
string="+3212345678"
n=3
string=string[0:n]+" "+string[n:]
string
'+32 12345678'
You can make a list which stores the number of characters space_list before a space, and add each character to a new list in a nested loop based on your space_list which adds a space right after the inner loop.
def format_num(space_list: list):
fmt_num = ""
count = 0
for space in space_list:
for s in range(space):
fmt_num += phn_num[count]
count += 1
fmt_num += " "
return fmt_num
phn_num = "+3212345678"
spaces = [3, 1, 3, 2, 2]
print(format_num(spaces))

Is there a way to replace the first and last three characters in a list of sequences using Python?

I am attempting to use Python to replace certain characters in a list of sequences that will be sent out for synthesis. The characters in question are the first and last three of each sequence. I am also attempting to add a * between each character.
The tricky part is that the first and last character need to be different from the other two.
For example: the DNA sequence TGTACGTTGCTCCGAC would need to be changed to /52MOErT/*/i2MOErG/*/i2MOErT/*A*C*G*T*T*G*C*T*C*C*/i2MOErG/*/i2MOErA/*/32MOErC/
The first character needs to be /52MOEr_/ and the last needs to be /32MOEr_/, where the _ is the character at that index. For the example above it would be T for the first and C for the last. The other two, the GT and GA would need to be /i2MOEr_/ modifications.
So far I have converted the sequences into a list using the .split() function. The end result was ['AAGTCTGGTTAACCAT', 'AATACTAGGTAACTAC', 'TGTACGTTGCTCCGTC', 'TGTAGTTAGCTCCGTC']. I have been playing around for a bit but I feel I need some guidance.
Is this not as easy to do as I thought it would be?
You can just use the divide and conquer algorithm. Here's my solution to achieve your goal.
dna = "TGTACGTTGCTCCGAC"
dnaFirst3Chars = '/52MOEr' + dna[0] + '/*/i2MOEr' + dna[1] + '/*/i2MOEr' + dna[2] + '/*'
dnaMiddle = '*'.join(dna[3:-3])
dnaLast3Chars = '*/i2MOEr' + dna[-3] + '/*i2MOEr' + dna[-2] + '/*/32MOEr' + dna[-1] + '/'
dnaTransformed = dnaFirst3Chars + dnaMiddle + dnaLast3Chars
print(dnaTransformed)
Output:
/52MOErT/*/i2MOErG/*/i2MOErT/*A*C*G*T*T*G*C*T*C*C*/i2MOErG/*i2MOErA/*/32MOErC/
UPDATE:
For simplicity, you can transform the above code in a function like this:
def dna_transformation(dna):
""" Takes a DNA string and returns the transformed DNA """
dnaFirst3Chars = '/52MOEr' + dna[0] + '/*/i2MOEr' + dna[1] + '/*/i2MOEr' + dna[2] + '/*'
dnaMiddle = '*'.join(dna[3:-3])
dnaLast3Chars = '*/i2MOEr' + dna[-3] + '/*i2MOEr' + dna[-2] + '/*/32MOEr' + dna[-1] + '/'
return dnaFirst3Chars + dnaMiddle + dnaLast3Chars
print(dna_transformation("TGTACGTTGCTCCGAC")) # call the function
Output: /52MOErT/*/i2MOErG/*/i2MOErT/*A*C*G*T*T*G*C*T*C*C*/i2MOErG/*i2MOErA/*/32MOErC/
Assuming there's a typo in your expected result and it should actually be
/52MOErT/*/i2MOErG/*/i2MOErT/*A*C*G*T*T*G*C*T*C*C*/i2MOErG/*/i2MOErA/*/32MOErC/ the code below will work:
# python3
def encode_sequence(seq):
seq_front = seq[:3]
seq_back = seq[-3:]
seq_middle = seq[3:-3]
front_ix = ["/52MOEr{}/", "/i2MOEr{}/", "/i2MOEr{}/"]
back_ix = ["/i2MOEr{}/", "/i2MOEr{}/", "/32MOEr{}/"]
encoded = []
for base, index in zip(seq_front, front_ix):
encoded.append(index.format(base))
encoded.extend(seq_middle)
for base, index in zip(seq_back, back_ix):
encoded.append(index.format(base))
return "*".join(encoded)
Read through the code and make sure you understand it. Essentially we're just slicing the original string and inserting the bases into the format you need. Each element of the final output is added to a list and joined by the * character at the end.
If you need to dynamically specify the number and name of the bases you extract from the front and back of the sequence you can use this version. Note that the {} braces tell the string.format function where to insert the base.
def encode_sequence_2(seq, front_ix, back_ix):
seq_front = seq[:len(front_ix)]
seq_back = seq[-len(back_ix):]
seq_middle = seq[len(front_ix):-len(back_ix)]
encoded = []
for base, index in zip(seq_front, front_ix):
encoded.append(index.format(base))
encoded.extend(seq_middle)
for base, index in zip(seq_back, back_ix):
encoded.append(index.format(base))
return "*".join(encoded)
And here's the output:
> seq = "TGTACGTTGCTCCGAC"
> encode_sequence(seq)
/52MOErT/*/i2MOErG/*/i2MOErT/*A*C*G*T*T*G*C*T*C*C*/i2MOErG/*/i2MOErA/*/32MOErC/
If you have a list of sequences to encode you can iterate over the list and encode each:
encoded_list = []
for seq in dna_list:
encoded_list.append(encode_sequence(seq))
Or with a list comprehension:
encoded_list = [encode_sequence(seq) for seq in dna_list)]

Is there a way to remove specific strings from indexes using a for loop?

I am trying to remake the built-in function for bin(x) for better understanding, I have got that part down, now the issue is how to dynamically remove the 0s when they are not necessary.
I have tried using replace() but it seems to be removing every suggested "0" I am unsure how to select the zeroes till it hits the first index in which there is a "1"
for eg:
if i have 0b00010010
___
0b00010010
^
I would like to select the numbers after the 0b and erase the 0s right after until "1"
def bin(x):
if x>0:
binary = ""
i = 0
while x>0 and i<=16:
string = str(int(x%2))
binary = binary+string
x/=2
i = i+1
d = binary[::-1]
ret = f"0b{d}"
return ret.replace("00","")
else:
x = abs(x)
binary = ""
i = 0
while x > 0 and i <=16:
string = str(int(x % 2))
binary = binary + string
x /= 2
i = i + 1
nd = binary[::-1]
ret = f"-0b{nd}"
return ret.replace("00","")
print(bin(8314))# 0b00010000001111010 this is the current out
0b00010000001111010 this is the current output
0b10000001111010 this is what I want
It might be better to simplify things by not generating those extra zeroes in the first place:
def bin(x):
prefix = ("-" if x < 0 else "")
x = abs(x)
bits = []
while x:
x, bit = divmod(x, 2) # division and remainder in one operation
bits.append(str(bit))
# Flip the bits so the LSB is on the right, then join as string
bit_string = ''.join(bits[::-1])
# Form the final string
return f"{prefix}0b{bit_string}"
print(bin(8314))
prints
0b10000001111010
You should take a look at lstrip():
>>> b = "00010000001111010"
>>> b.lstrip("0")
'10000001111010'
Of course, make sure to prefix the binary with "0b" after calling lstrip().
Scott Hunter brought up a nice solution to your problem, however, if you want to use a for loop, consider trying the following:
binary = "0b00010000001111010"
start_index = binary.find("b")
for index in range(b+1, len(binary)):
if binary[index] == 0:
binary = binary[0:index:] + binary[index+1::]
else:
break

How to add a integer to a string?

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))

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