How do you pad a number 12345-9 to display as 12345-09? I tried split and replace but they don't work on integers. If I convert it to a string, it gets rid of the numbers after the hyphen.
As Adam said, split on the hyphen, pad the number, and then rejoin.
s = "12345-9"
sp = s.split("-")
sp[1] = "%02d" % int(sp[1])
s = "-".join(sp)
print s
>>> s = '12345-9'
>>> '%s-%02i' % tuple(int(v) for v in s.split('-'))
'12345-09'
Related
Write the function Separator that:
Input: inString -- random string scalar mixed with numbers & letters
Tasks:
Seperate Numbers & Letters
Calculate Sum of Numbers
Count Number of Letters (the white spaces counted)
Output:
numbers, string scalar of all numbers in inString with same order.
letters, string scalar of all letters in inString with same order, and white spaces Does Not removed.
sumofNumbers, double precision scalar of sum of all numbers in inString.
numberofLetters, double precision scalar to count all letters in inString, white spaces counted.
Expected Result:
inString: "eng12in13e143e553rin154g 6p547ro548bl645em 8s65ol9v56ing"
numbers: "12131435531546547548645865956"
letters: "engineering problem solving"
sumofNumbers: 131
numberofLetters: 27
Here's My Code:
function [numbers, letters, sumofNumbers, numberofLetters]=Separator(inString)
%Insert your code here
indexNum = regexp(char(inString), '[0-9]')
numbers = []
for i = 1:numel(indexNum)
numbers = [numbers , inString{1}(indexNum(i))]
end
% numbers
numbers = string(numbers)
% sumofNumbers
sumofNumbers = 0
for i = 1:numel(indexNum)
sumofNumbers = sumofNumbers + str2num(numbers{1}(i))
end
words = split(inString)
letters = []
count = 0
for i = 1:numel(words)
indexLett = regexp(char(words(i)), '[a-z]')
count = count + numel(indexLett)
for j = 1:numel(indexLett)
letters = [letters, words{i}(indexLett(j))]
end
letters = strcat(string(letters), " ")
letters = char(letters)
end
% letters
letters = strip(string(letters))
comb = split(letters)
letters = join(comb)
% number of Literal Letters
numofTrueLetters = count
% numberofLetters
numberofLetters = 0
numberofLetters = strlength(letters)
end
The Code Returns Exactly As the Expected:
numbers =
"12131435531546547548645865956"
letters =
"engineering problem solving"
sumofNumbers =
131
numberofLetters =
27
However, the MATLAB Grader gives this Answer: "Variable Letters Has an Incorrect Value" and I was confused.
I would be very appreciated if someone could point out the mistake or the error, thank you!
Alright I got this!
I modified this line, before "[a-z]" and now is "[A-Za-z]" which checks all upper and lower cases for case-insensitivity.
indexLett = regexp(char(words(i)), '[A-Za-z]')
By this way, the indexLett would record all the indexes in the string that has alphabetic letters regardless of case-sensitive,
so for more inputs like
"Apple is good for health"
or
"A42pp3113le31 is 31g11oo456d fo442r h105ea422l44t2h"
could be counted as the capitalized words in the string.
In Matlab, is it possible to create a string like:
f1-*f2-*f3-*f4-*f5-*f6
giving only as parameters:
f, 1:6 and -* ?
I tried:
for i=1:6; str = strcat(str, sprintf('f%d %s',i,'-* ')); end
but it doesn't work very well and seems ineficient for a larger number of files... Perhaps a regexp would be more suitable here?
This gives you the string with extra trailing separator:
str = sprintf('f%d-*', 1:6)
Perhaps you can just remove the last two characters from this. In general, a single sprintf for an array input is quite efficient.
strjoin for using -* as a delimiter, and strcat for combining the numbers with f:
>> strjoin(strcat('f',sprintfc('%d',1:6)),'-*')
ans =
f1-*f2-*f3-*f4-*f5-*f6
Because strcat accepts cell arrays, no loop is needed.
% //Data:
letter = 'f';
numbers = 1:6;
separator = '-*';
%// Let's go:
num = mat2cell(num2str(numbers(:)), ones(1,numel(numbers))); %// cell array
%// of strings from the numbers. Those strings may contain spaces.
%// Those will be removed later
s = strcat('f',num,'-*'); %// concatenate letter and separator to each number
s = [s{:}]; %// contatenate all
s = s(1:end-numel(separator)); %// remove last separator
s(s==' ') = []; %// remove spaces (in case of several-digit numbers)
I am trying to code a program that will insert specific numbers before parts of an input, for example given the input "171819-202122-232425" I would like it to split up the number into pieces and use the dash as a delimiter. I have split up the number using list(str(input)) but have no idea how to insert the appropriate numbers. It has to work for any number Thanks for the help.
Output =
(number)17
(number)18
(number)19
(number+1)20
(number+1)21
(number+1)22
(number+2)23
(number+2)24
(number+2)25
You could use split and regexps to dig out lists of your numbers:
Code
import re
mynum = "171819-202122-232425"
start_number = 5
groups = mynum.split('-') # list of numbers separated by "-"
number_of_groups = xrange(start_number , start_number + len(groups))
for (i, number_group) in zip(number_of_groups, groups):
numbers = re.findall("\d{2}", number_group) # return list of two-digit numbers
for x in numbers:
print "(%s)%s" % (i, x)
Result
(5)17
(5)18
(5)19
(6)20
(6)21
(6)22
(7)23
(7)24
(7)25
Try this:
Code:
mInput = "171819-202122-232425"
number = 9 # Just an example
result = ""
i = 0
for n in mInput:
if n == '-': # To handle dash case
number += 1
continue
i += 1
if i % 2 == 1: # Each two digits
result += "\n(" + str(number) + ")"
result += n # Add current digit
print result
Output:
(9)17
(9)18
(9)19
(10)20
(10)21
(10)22
(11)23
(11)24
(11)25
I'm making a program that scrambles words for fun and I've hit a roadblock. I am attempting to switch all the letters in a string and I'm not quite sure how to go about it (hello = ifmmp). I've looked all around and haven't been able to find any answers to this specific question. Any help would be great!
You want a simple randomized cypher? The following will work for all lowercase inputs, and can easily be extended.
import random
import string
swapped = list(string.lowercase)
random.shuffle(swapped)
cipher = string.maketrans(string.lowercase, ''.join(swapped))
def change(val):
return string.translate(val, cipher)
You can probably modify this example to achieve what you need. Here every vowel in a string is replaced by its vowel position:
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
# this is the output
"th3s 3s str3ng 2x1mpl2....w4w!!!"
Try maketrans in combination with the string.translate function. This code removes letters from your word from the letters you are scrambling with first. If you just want lowercase only use string.lowercase instead of string.letters.
>>> import string, random
>>> letters = list(string.letters)
>>> random.shuffle(letters)
>>> letters = "".join(letters)
>>> word = 'hello'
>>> for letter in word:
... letters = letters.replace(letter, '')
...
>>> transtab = string.maketrans(word, letters[:len(word)])
>>> print word.translate(transtab)
XQEEN
The "scrambling" you appear to be after is called Caesar's cipher, with a right shift of 1. The following Python will achieve what you're after:
def caesar(str):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
# Move the last 1 chars to the start of the string
toalpha = fromalpha[1:] + fromalpha[:1]
# Make it work with capital letters
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)
If you're interested in the general case, this function will do the job. (Note that it is conventional to express Caesar ciphers in terms of left shifts, rather than right.)
def caesar(str, lshift):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
toalpha = fromalpha[-lshift:] + fromalpha[:-lshift]
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)
I want to ask about regExp, I need regExp, which work like this:
input = '569/A';
result = '569-1';
input = '569/a';
result = '569-2';
input = '569/B';
result = '569-3';
input = '569/b';
result = '569-4';
You definitely understand the pattern which I want. '/' or '\' converted in '-', Characters should be converted in numeric with proper sequence A = 1, a = 2, B=3, b=4. Uppercase on odd numeric and Lowercase on even numeric
Try to use .replace() - it will be much easier.
http://www.w3schools.com/jsref/jsref_replace.asp
.replace('/','-').replace('A','1').replace('a','2').replace('B','3').replace('b','4');