python string manipulation to match windows firewall syntax - python

I have a string like so:
string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255" #(white space sep)
how would you go from it to this format:
string = "27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255"
**the string will have unknown length , the elements number will allways be even.
I've looked at some close examples and got confused..
what is the best easy way doing that?

# Create a new list containing the ips
str_elems = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255".split()
# Use a format string to build the new representation, where each list element is assigned a spot in the string
# We use the * operator to convert the single list into multiple arguments for the format
new_str = ("{}-{},"*(len(str_elems)/2)).format(*str_elems).rstrip(',')

For a general solution, you can iterate over your split string in chunks of 2.
s = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255".split()
print(",".join(["-".join(s[i:i + 2]) for i in range(0, len(s), 2)]))
#'27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255'
Join the inner chunks with a "-" and finally join the whole thing with ","

string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255"
ip_list = string.split(" ") # split the string to a list using space seperator
for i in range(len(ip_list)): # len(ip_list) returns the number of items in the list (4)
# range(4) resolved to 0, 1, 2, 3
if (i % 2 == 0): ip_list[i] += "-" # if i is even number - concatenate hyphen to the current IP string
else: ip_list[i] += "," # otherwize concatenate comma
print("".join(ip_list)[:-1]) # "".join(ip_list) - join the list back to a string
# [:-1] trims the last character of the result (the extra comma)

Related

Split a string if character is present else don't split

I have a string like below in python
testing_abc
I want to split string based on _ and extract the 2 element
I have done like below
split_string = string.split('_')[1]
I am getting the correct output as expected
abc
Now I want this to work for below strings
1) xyz
When I use
split_string = string.split('_')[1]
I get below error
list index out of range
expected output I want is xyz
2) testing_abc_bbc
When I use
split_string = string.split('_')[1]
I get abc as output
expected output I want is abc_bbc
Basically What I want is
1) If string contains `_` then print everything after the first `_` as variable
2) If string doesn't contain `_` then print the string as variable
How can I achieve what I want
Set the maxsplit argument of split to 1 and then take the last element of the resulting list.
>>> "testing_abc".split("_", 1)[-1]
'abc'
>>> "xyz".split("_", 1)[-1]
'xyz'
>>> "testing_abc_bbc".split("_", 1)[-1]
'abc_bbc'
You can use list slicing and str.join in case _ is in the string, and you can just get the first element of the split (which is the only element) in the other case:
sp = string.split('_')
result = '_'.join(sp[1:]) if len(sp) > 1 else sp[0]
All of the ways are good but there is a very simple and optimum way for this.
Try:
s = 'aaabbnkkjbg_gghjkk_ttty'
try:
ans = s[s.index('_')+1:]
except:
ans = s
Ok so your error is supposed to happen/expected because you are using '_' as your delimiter and it doesn't contain it.
See How to check a string for specific characters? for character checking.
If you want to only split iff the string contains a '_' and only on the first one,
input_string = "blah_end"
delimiter = '_'
if delimiter in input_string:
result = input_string.split("_", 1)[1] # The ",1" says only split once
else:
# Do whatever here. If you want a space, " " to be a delimiter too you can try that.
result = input_string
this code will solve your problem
txt = "apple_banana_cherry_orange"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("_", 1)
print(x[-1])

How to edit a string to add a variable at a particular place in python?

I have a variable:
a = 2
and I have this string:
"//media.boohooman.com/i/boohooman/mzz11035_black_xl/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
I want edit this string so I can add variable, a, at a specific place in this string, after "mzz11035_black_xl", to make the whole string look like:
"//media.boohooman.com/i/boohooman/mzz11035_black_xl_2/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
What options do I have to achieve this goal. I know that there are some hard coded ways where I can count the characters before and after a specific place and do slicing, but I am looking for some more general method so that it would work even if the strings change a bit. eg.
"//media.boohooman.com/i/boohooman/mzz11035_blue_xl/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
or
"//media.boohooman.com/i/boohooman/mzz11035_blue_s/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
Thanks.
You need to use f string or the format() function:
var = "_2"
f"//media.boohooman.com/i/boohooman/mzz11035_black_xl{var}/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
or
var = "_2"
"//media.boohooman.com/i/boohooman/mzz11035_black_xl{}/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp".format(var)
if the position of the "mzz11035_black_xl" is changing you can do this:
var = "_2"
split_with = "mzz11035_black_xl"
initial_string = "//media.boohooman.com/i/boohooman/mzz11035_black_xl{var}/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
# split the string into two parts
split_string = initial_string.split(split_with)
# Add the parts back with any sting in between
resulting_string = split_string[0] + split_with + var + split_string[1]
but in this case, you need to make sure that you have only one "mzz11035_black_xl" in your string.
If the string is changing but the link structure doesn't change you can try splitting with "/" (not elegant now but can be optimized)
var = "_2/"
split_with = "/"
initial_string = "//media.boohooman.com/i/boohooman/mzz11035_blue_s/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
# initializing K
K = 6
# printing original string
print("The original string is : " + str(initial_string))
# Using split() + join()
# Split string on Kth Occurrence of Character
temp = initial_string.split(split_with)
resulting_tuple = split_with.join(temp[:K]), split_with.join(temp[K:])
# Convert to list and insert any string
resulting_list = list(resulting_tuple)
resulting_list.insert(1,var)
# convert to string
resulting_string = ""
resulting_string = resulting_string.join(list(resulting_list))
print("Is list after Kth split is: " + resulting_string)
Output:
"Is list after Kth split is : //media.boohooman.com/i/boohooman/mzz11035_blue_s_2/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
you can use replace() function.
Syntax:
string.replace(old, new, count)
Parameters:
old – old substring you want to replace.
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with the new substring. (Optional)
Return Value:
It returns a copy of the string where all occurrences of a substring are replaced with another substring.
Code sample:
a = "2"
str_to_replace = "//media.boohooman.com/i/boohooman/mzz11035_black_xl/mens-black-man-signature-embroidered-t-shirt?$product_page_main_magic_zoom$&fmt=webp"
old = "mzz11035_black_xl"
new = "mzz11035_black_xl_{}".format(a)
str_replaced = str_to_replace.replace(old, new)
print(str_replaced)

How to get all possible incremental values between two mixed strings in Python?

I am new to Python (and programming, in general) and hoping to see if someone can help me. I am trying to automate a task that I am currently doing manually but is no longer feasible. I want to find and write all strings between two given strings. For example, if starting and ending strings are XYZ-DF 000010 and XYZ-DF 000014, the desired output should be XYZ-DF 000010; XYZ-DF 000011; XYZ-DF 000012; XYZ-DF 000013; XYZ-DF 000014. The prefix and numbers (and their padding) are not always the same. For example, next starting and ending strings in the list could be ABC_XY00000001 and ABC_XY00000123. The prefix and padding for any pair of starting and ending strings, though, will always be the same.
I think I need to separate the prefix (includes any alphabets, spaces, underscore, hyphen etc.) and numbers, remove padding from the numbers, increment the numbers by 1 from starting number to ending number for every starting and ending strings in a second loop, and then finally get the output by concatenation.
So far this is what I have:
First, I read the 2 columns that contain a list of starting and ending strings in a csv into lists using pandas:
columns = ['Beg', 'End']
data = pd.read_csv('C:/Downloads/test.csv', names=columns, header = None)
begs = data.Beg.tolist()
ends= data.End.tolist()
Next, I loop over "begs" and "ends" using the zip function.
for beg, end in zip(begs,ends):
Inside the loop, I want to iterate over each string in begs and ends (one pair at a time) and perform the following operations on them:
1) Use regex to separate the characters (including alphabets, spaces, underscore, hyphen etc.) from the numbers (including padding) for each of the strings one at a time.
start = re.match(r"([a-z-_ ]+)([0-9]+)", beg, re.I) #Let's assume first starting string in the begs list is "XYZ-DF 000010" from my example above
prefix = start.group(1) #Should yield "XYZ-DF "
start_num = start.group(2) #Should yield "000010"
padding = (len(start_num)) #Yields 6
start_num_stripped = start_num.lstrip("0") #Yields 10
end = re.match(r"([a-z-_ ]+)([0-9]+)", end, re.I) #Let's assume first ending string in the ends list is "XYZ-DF 000014" from my example above
end_num = end.group(2) #Yields 000014
end_num_stripped = end_num.lstrip("0") #Yields 14
2) After these operations, run a nested while loop from start_num_stripped until end_num_stripped
output_string = ""
while start_num_stripped <= end_num_stripped:
output_string = output_string+prefix+start_num_stripped.zfill(padding)+"; "
start_num_stripped += 1
Finally, how do I write the output_string for each pair of starting and ending strings to a csv file that contains 3 columns containing the starting string, ending string, and their output string? An example of an output in csv format is given below (newline after each row is for clarity and not needed in the output).
"Starting String", "Ending String", "Output String"
"ABCD-00001","ABCD-00003","ABCD-00001; ABCD-00002; ABCD-00003"
"XYZ-DF 000010","XYZ-DF 000012","XYZ-DF 000010; XYZ-DF 000011; XYZ-DF 000012"
"BBB_CC0000008","BBB_CC0000014","BBB_CC0000008; BBB_CC0000009; BBB_CC0000010; BBB_CC0000011; BBB_CC0000012; BBB_CC0000013; BBB_CC0000014"
You could find the longest trailing numeric suffix using a regular expression. Then simply iterate numbers from start to end appending them (with leading zeros) to the common prefix:
import re
startString = "XYZ-DF 000010"
endString = "XYZ-DF 000012"
suffixLen = len(re.findall("[0-9]*$",startString)[0])
start = int("1"+startString[-suffixLen:])
end = int("1"+endString[-suffixLen:])
result = [ startString[:-suffixLen]+str(n)[1:] for n in range(start,end+1) ]
csvLine = '"' + '","'.join([ startString,endString,";".join(result) ]) + '"'
print(csvLine) # "XYZ-DF 000010","XYZ-DF 000012","XYZ-DF 000010;XYZ-DF 000011;XYZ-DF 000012"
Note: using int("1" + suffix) causes numbers in the range to always have 1 more digit than the length of the suffix (1xxxxx). This makes it easy to get the leading zeroes by simply dropping the first character after turning them back into strings str(n)[1:]
Note2: I'm not familiar with pandas but I'm pretty sure it has a way to write a csv directly from the result list rather than formatting it manually as I did here in csvLine.

How to add a number of char on a string in python

Hello is there a function that will get a string S and a number n and will add (n-1) # at the start and (n-1) % at the end. In python. I know how to add a char but not a number of them. Example S= abracatabra and n =3 result : ##abracatabra%%
I think this does what you want:
string = "test"
n = 3
for i in range(1,n):
string = "#"+string+"%"
print(string)
The version of #idjaw is better optimized that this solution but remember you can just add strings using +.
Alternative version:
string = "#"*(n-1)+string+"%"*(n-1)
This can also be achieved using Python's Format Specification Mini-Language specification. This allows pad characters and widths to be specified as follows:
n = 5
text = "abracatabra"
print "{:#>{w}}{}{:%>{w}}".format("", text, "", w=n-1)
This would display:
####abracatabra%%%%
In effect this is printing 3 items, firstly an empty string padded with n-1 # fill characters. Secondly the text string. Lastly another empty string padded with n-1 % fill characters.

python string, delete character, count from right

I have some strings I created with elements coming from many sources, number of elements will vary each time the program is run; I created a sample string that my program creates now.
I want to count in [:-3] for the following string and delete the last comma:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
So my string looks like:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
I just cant quite get there, help appreciated.
To remove the third last character from the string you can use:
string[:-3] + string[-2:]
>>> string = "hellothere"
>>> string[:-3] + string[-2:]
'hellothre'
I would use rsplit to split on the right most occurrence of a substring (limiting to two results) and then join them with an empty string
''.join(s.rsplit(',', 2))
a = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
a[:len(a) - 2] + a[len(a) - 1:]
You could obviously use different expressions in the brackets, I just wanted to show that you could use any expressions you wanted.
you can try with rfind to find the last comma
s = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
idx = s.rfind(",")
s[:idx]+s[idx+1:]
you get,
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
Using regex:
>>> print re.sub(r ",(?=[^.]*$)", r '', s)
{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}
This will match a ',' all before a any potential NOT ','. It matches the last ',' right before the end of a string.

Categories

Resources