Python: Finding and Pointing to the Midpoint of a string
I just started learning Python (as my first language, so I know next to nothing) and have come across this problem.
Find the midpoint of a word, and poin开发者_StackOverflow社区t to it using a caret "^".
Example,
Computer
^
Thanks for any tips anyone could give me.
Use len
, which finds the length of the object.
>>> x = "Computer"
>>> x[len(x)/2 - 1]
'p'
-
# a.py
x = "Computer"
print x
print (" " * (len(x)/2 - 1)) + "^"
# % python a.py
Computer
^
text='Computer'
print(text)
print('{0:^{1}}'.format('^',len(text)))
{0:...}
tellsformat
to replace replace itself with the first argument,'^'
.{1}
gets replaced by the second argument,len(text)
.^{1}
tellsformat
to center the text, and make the total width equal tolen(text)
.
So the docs for the full specs on format.
The mid point depends on odd or even length of a string. So, if it is an odd length the middle will be exactly len/2+1 if it is an even length, you should decide what is the middle for you (len/2 or len/2+1)
x="Computer"
if len(x)%2: return x[len(x)/2+1]
else: return x[len(x)/2]
I like this format better because it's simple. It just uses the round()
function. But this is only to find the midpoint and not to execute the ^
, but I assume that should be self-explanatory.
my_str2 = "computer"
output = round(len(my_str2)/2)
print(my_str2[output])
精彩评论