I am trying to plot the location of ~4k postcodes onto a UK map, I am using a library that can take in the postcode and kick back latitude, longitude etc.., however the postcode must always contain a space before the last 3 characters in the string, for example:
'AF23 4FR' would be viable as the space is before the last 3 chars in the string..
'AF234FR' would not be allowed as there is no space..
I have to go over each item within my list and check there is a space before the n-3 position in the string, I can do this with a simple for loop but I would prefer to do this with a reduce function. I am struggling to workout how I would rework the check and logic of the following into a reduce method, would it even be worth it in this scenario:
for index, p in enumerate(data_set):
if (p.find(' ') == -1):
first = p[:len(p)]
second = p[len(first):]
data_set[index] = first + ' ' + second
You're pretty much there... Create a generator with spaces removed from your string, then apply slicing and formatting, and use a list-comp to generate a new list of foramtted values, eg:
pcs_without_spaces = (pc.replace(' ', '') for pc in data_set)
formatted = ['{} {}'.format(pc[:-3], pc[-3:]) for pc in pcs_without_spaces)
That way, you don't need additional logic on whether it's got a space or not already in it, as long as your postcode is going to be valid after slicing, just removing the spaces and treating everything with the same logic is enough.
Related
Just started learning python. And it looks to me that rjust() method is counting string that I'm trying to justify in justifying length.
Let me clarify a little bit, the book I'm using to study python had this type of small program:
order = "First\nSecond\nThird"
print("The order is: ", order)
Whose output is:
The order is: First
Second
Third
And I thought what could I change to make output as (desired output),
The order is: First
Second
Third
Well there may be very easy way to solve this but bear in mind I just started learning python. I tried formatting to no avail. After learning about list I came up with this solution,
order = "First\nSecond\nThird"
listed_order = order.split("\n")
length_of_list = len(listed_order)
print_line = "The order is: "
length = len(print_line)
print(print_line + listed_order[0])
for i in range(1, length_of_list):
print(listed_order[i].rjust(length))
But the output is,
The order is: First
Second
Third
That means rjust() method is counting Second and Third to make justified length of 14, while I wanted them to start from 14. Second has 8 spaces in front of it to make justified length of 14, while Third has 9 spaces.
So, what can I do to get my desired output? If there is another way to solve this let me know.
What you describe is left-justified, but with an additional offset (also known as indentation).
Instead of
print(listed_order[i].rjust(length))
simply do
print(' ' * length + listed_order[i])
If there is nothing to the right of listed_order[i], you don't need to use ljust either.
You might want to take a look at textwrap.indent, which lets you indent whole blocks of text without splitting the lines manually.
You don't have to do such things: length_of_list = len(listed_order). You can run your loop without checking length of the list:
for i in listed_order:
print(i.rjust(length))
EDIT:
As pointed in the comments, this would also print first element which we want to skip. You can do it by telling python to process from second element by adding [1:], which means from element of index 1 (which is second after index 0) untill end), so:
for i in listed_order[1:]:
print(i.ljust(length))
Now to the core.
What you need is the number of whitespaces. You can get it by running this:
number_of_whitespaces = len("The order is: ")
And then print it out before each line:
print(' ' * number_of_whitespaces, end='')
Full solution here:
#!/usr/bin/env python3
order = "First\nSecond\nThird"
print("The order is: ", order)
orders = order.split()
whitespaces = len('The order is: ')
print('The order is: {}'.format(orders[0]))
for o in orders[1:]:
print(' ' * whitespaces, end='')
print(o)
EDIT2: Added missing colon, Changed rjust to ljust
EDIT3: Added full solution
Python beginner here, sorry if this is a dumb question.
So I have a long string, and I need to add a character in very specific areas of the strings. For example, a | after character number 23, 912, and 1200. I read this Add string in a certain position in Python, but it only works for adding one character.
Also, the solution needs to be expandable, not just do it 3 times. The code I'm making can have lots of different locations with where I want the character to be.
With reference to the link that you posted Add string in a certain position in Python;
If you would like to repeat the operation for different values, you could create a list containing all index positions where you would like your | character to be inserted.
For example,
>>> l = [1, 3, 4]
>>> s = "abcdef"
>>> for i in l:
>>> s = s[:i] + "|" + s[i:] # as suggested in your link
>>> s
'a|b||cdef'
This will allow you to repeat the process for the set of values that you provide in the list. You could also define a function to assist in this, which I could explain if this method is insufficient!
Note, however, that this will insert the character relative to the current iteration. That is, in this example, after adding the | at position 1, the next insert position, 3, is different from what it was before the first insert. You could avoid this (if you want) by including a counter variable to offset all the index positions by the number of inserts that have been executed (will require initial list to be ordered).
Not so good at python, hope I can help
According to that site you went to, you can make a while loop to solve the problem
The code should look something like this
def insert_dash(string, index, addin):
return string[:index] + addin + string[index:]
alldone = False
string = input("String: ")
index = " "
while index:
index = input("Index: ")
addin = input("Add into: ")
string = insert_dash(string, index, addin)
Hope it helps!
PS: I have NOT tried the code, but I think it will work
Okay, I'm really new to Python and have no idea how to do this:
I need to take a string, say 'ABAB__AB', convert it to a list, and then take the leading index of the pair I want to move and swap that pair with the __. I think the output should look something like this:
move_chars('ABAB__AB', 0)
'__ABABAB'
and another example:
move_chars('__ABABAB', 3)
'BAA__BAB'
Honestly have no idea how to do it.
Python strings are immutable, so you can't really modify a string. Instead, you make a new string.
If you want to be able to modify individual characters in a string, you can convert it to a list of characters, work on it, then join the list back into a string.
chars = list(str)
# work on the list of characters
# for example swap first two
chars[0], chars[1] = chars[1], chars[0]
return ''.join(chars)
I think this should go to the comment section, but I can't comment because of lack of reputation, so...
You'll probably want to stick with list index swapping, rather than using .pop() and .append(). .pop() can remove elements from arbitrary index, but only one at once, and .append() can only add to the end of the list. So they're quite limited, and it would complicate your code to use them in this kind of problems.
So, well, better stick with swapping with index.
The trick is to use list slicing to move parts of the string.
def move_chars(s, index):
to_index = s.find('__') # index of destination underscores
chars = list(s) # make mutable list
to_move = chars[index:index+2] # grab chars to move
chars[index:index+2] = '__' # replace with underscores
chars[to_index:to_index+2] = to_move # replace underscores with chars
return ''.join(chars) # stitch it all back together
print(move_chars('ABAB__AB', 0))
print(move_chars('__ABABAB', 3))
I have this string 553943040 21% 50.83MB/s 0:00:39
The length of the numbers can vary
The percent can contain one or two numbers
The spaces between the start of the string and the first number may vary
I need to extract the first number, in this case 553943040
I was thinking that the method could be to:
1) Replace the percent with a separator. something like:
string=string.replace("..%","|") # where the "." represent any character, even an space.
2) Get the first part of the new string by cutting everything after the separator.
string=string.split("|")
string=string[0]
3) Remove the spaces.
string=string.strip()
I know that the stages 2 and 3 works, but I'm stocked on the first. Also if there is any better method of getting it would be great to know it!
Too much work.
>>> '553943040 21% 50.83MB/s 0:00:39'.split()[0]
'553943040'
I am working with python and I am new to it. I am looking for a way to take a string and split it into two smaller strings. An example of the string is below
wholeString = '102..109'
And what I am trying to get is:
a = '102'
b = '109'
The information will always be separated by two periods like shown above, but the number of characters before and after can range anywhere from 1 - 10 characters in length. I am writing a loop that counts characters before and after the periods and then makes a slice based on those counts, but I was wondering if there was a more elegant way that someone knew about.
Thanks!
Try this:
a, b = wholeString.split('..')
It'll put each value into the corresponding variables.
Look at the string.split method.
split_up = [s.strip() for s in wholeString.split("..")]
This code will also strip off leading and trailing whitespace so you are just left with the values you are looking for. split_up will be a list of these values.