Padding a number with leading zeros has been answered here. But in my case I have a string character followed by digits. I want to add leading zeros after the string character, but before the digits, keeping the total length to 4. For example:
A1 -> A001
A12 -> A012
A123 -> A123
I have the following code that gets me what I want, but is there a shorter way to do this without using re to split my string into text and numbers first?
import re
mystr = 'A4'
elements = re.match(r"([a-z]+)([0-9]+)", mystr, re.I)
first, second = elements.groups()
print(first + '{:0>3}'.format(second))
output = A004
You could use the following to avoid using re:
def pad_center(s):
zeros = '0' * (4 - len(s))
first, *the_rest = list(s)
return first + zeros + ''.join(the_rest)
print(pad_center('A1'))
print(pad_center('A12'))
print(pad_center('A123'))
Or, if you want to use format() you could try this:
def pad_center(s):
zeros = '0' * (4 - len(s))
first, *the_rest = list(s)
return '{}{}{}'.format(first, zeros, ''.join(the_rest))
However, I am not aware of any way to add padding to the center of a string with the format string syntax without prior processing.
Related
For example, If my string was 'HelloWorld'
I want the output to be ######orld
My Code:
myString = 'ThisIsAString'
hashedString = string.replace(string[:-4], '#')
print(hashedString)
Output >> #ring
I expected the output to have just one # symbol since it is replacing argument 1 with argument 2.
Can anyone help me with this?
You could multiply # by the word length - 4 and then use the string slicing.
myString = 'HelloWorld'
print('#' * (len(myString) - 4) + myString[-4:])
myString = 'ThisIsAString'
print('#' * (len(myString) - 4) + myString[-4:])
string.replace(old, new) replaces all instances of old with new. So the code you provided is actually replacing the entire beginning of the string with a single pound sign.
You will also notice that input like abcdabcd will give the output ##, since you are replacing all 'abcd' substrings.
Using replace, you could do
hashes = '#' * len(string[:-4])
hashedString = string.replace(string[:-4], hashes, 1)
Note the string multiplication to get the right number of pound symbols, and the 1 passed to replace, which tells it only to replace the first case it finds.
A better method would be to not use replace at all:
hashes = '#' * (len(string) - 4)
leftover = string[-4:]
hashedString = hashes + leftover
This time we do the same work with getting the pound sign string, but instead of replacing we just take the last 4 characters and add them after the pound signs.
I used beautifulsoup and I got a result form .get_text(). The result contains a long text:
alpha = ['\n\n\n\nIntroduction!!\nGood\xa0morning.\n\n\n\nHow\xa0are\xa0you?\n\n']
It can be noticed that the number of \n is not the same, and there are \xa0 for spacing.
I want to slice every group of \n (\n\n or \n\n\n or \n\n\n\n ) and replace \xa0 with a space in a new list, to look like this:
beta = ['Introduction!!','Good morning.','How are you?']
How can I do it?
Thank you in advance.
I wrote a little script that solves your problem:
alpha = ['\n\n\n\nIntroduction!!\nGood\xa0morning.\n\n\n\nHow\xa0are\xa0you?\n\n']
beta = []
for s in alpha:
# Turning the \xa0 into spaces
s = s.replace('\xa0',' ')
# Breaking the string by \n
s = s.split('\n')
# Explanation 1
s = list(filter(lambda s: s!= '',s))
# Explanation 2
beta = beta + s
print(beta)
Explanation 1
As there is some sequences of \n inside the alpha string, the split() will generate some empty strings. The filter() that I wrote removes them from the list.
Explanation 2
When the s string got split, it turns into a list of strings. Then, we need to concatenate the lists.
I'm using python 3.x. I'm trying to get the (int) number at the end of a string with format
string_example_1 = l-45-98-567-567-12
string_example_2 = s-89-657
or in general, a single lowercase letter followed by a number of integers separated by '-'. What I need is to get the last number (12 and 657 in these cases). I have archived this with the function
def ending(the_string):
out = ''
while the_string[-1].isdigit():
out = the_string[-1] + out
the_string = the_string[:-1]
return out
but I'm sure there must be a more pythonic way to do this. In a previous instance I check manually that the string starts the way I like by doing something like
if st[0].isalpha() and st[1]=='-' and st[2].isdigit():
statement...
I would just split the string on -, take the last of the splits and convert it to an integer.
string_example_1 = "l-45-98-567-567-12"
string_example_2 = "s-89-657"
def last_number(s):
return int(s.split("-")[-1])
print(last_number(string_example_1))
# 12
print(last_number(string_example_2))
# 657
Without regular expressions, you could reverse the string, take elements from the string while they're still numbers, and then reverse the result. In Python:
from itertools import takewhile
def extract_final_digits(s):
return int(''.join(reversed(list(takewhile(lambda c: c.isdigit(), reversed(s))))))
But the simplest is to just split on a delimiter and take the final element in the split list.
Define a function called repeat_middle which receives as parameter one string (with at least one character), and it should return a new string which will have the middle character/s in the string repeated as many times as the length of the input (original) string.
Notice that if the original string has an odd number of characters there is only one middle character. If, on the other hand, if the original string has an even number of characters then there will be two middle characters, and both have to be repeated (see the example).
Additionally, if there is only one middle character, then the string should be surrounded by 1 exclamation sign in each extreme . If , on the other hand, the original string has two middle characters then the returned string should have two exclamation signs at each extreme.
As an example, the following code fragment:
print (repeat_middle("abMNcd"))
should produce the output:
!!MNMNMNMNMNMN!!
Try the following:
def repeat_middle(string):
l = len(string)
if l % 2 == 0:
return "!!{}!!".format(string[int(l / 2 - .5) : int(l / 2 + 1.5)] * l)
else:
return "{}".format(string[int(l / 2)] * l)
odd = "ham"
even = "spam"
print("Original odd length string: {}".format(odd))
print("Returned string: {}".format(repeat_middle(odd)))
print("")
print("Original even length string: {}".format(even))
print("Returned string: {}".format(repeat_middle(even)))
Where the sample output is:
Original even length string: spam
Returned string: !!papapapa!!
Original odd length string: ham
Returned string: aaa
You will find that print(repeat_middle("abMNcd")) does indeed output !!MNMNMNMNMNMN!!.
How do I call out a particular digit from a number. For example: bringing out 6 from 768, then using 6 to multiply 3. I've tried using the code below, but it does not work.
digits = []
digits = str(input("no:"))
print (int(digits[1] * 5))
If my input is 234 since the value in[1] is 3, how can I multiply the 3 by 5?
input() returns a string (wether or not you explicitly convert it to str() again), so digits[1] is still a single character string.
You need to convert that single digit to an integer with int(), not the result of the multiplication:
print (int(digits[1]) * 5)
All I did was move a ) parenthesis there.
Your mistake was to multiply the single-character string; multiplying a string by n produces that string repeated n times.
digits[1] = '3' so digits[1] * 5 = '33333'. You want int(digits[1]) * 5.