r/pythonhelp • u/[deleted] • Dec 12 '20
[Program for School, 3.8.2] I need some kind of mathematical operation that can make it so that strings of ANY length can be made equal in length. I am new to Python and not the best at math, so help is greatly appreciated.
Variable legend:
stra = String A
strb = String B
stralen = Length of String A
strblen = Length of String B
This code is very rudimentary as my course is designed for beginners, but everything works apart from the math. How can I change the math in my code so that the two strings are the same length when appended, no matter the length of either string?
I have all strlen values printed for the sake of convenience.
### 3. Given two strings, append them together and print the result. However, if the strings are different lengths, omit characters from the longer string so it is the same length as the shorter string. So "Hello" and "Hi" yield "loHi". The strings may be any length.
###
stra = "Hello"
strb = "Wow"
stralen = len(stra)
strblen = len(strb)
print (stralen, strblen)
if stralen == strblen:
print (stra+strb)
elif stralen > strblen:
stralen = (stralen // strblen)
print (stralen, strblen)
print (stra [0:stralen]+strb)
elif stralen < strblen:
strblen = (strblen // stralen)
print (stralen, strblen)
print (stra+strb[0:strblen])
1
u/socal_nerdtastic Dec 12 '20
Find the smallest length (the
min()function can help) and then just slice both strings by that amount.