Feb-24-2018, 02:01 PM
(Feb-24-2018, 05:13 AM)volcano Wrote: e.g print('abc','def') = > this will give abcdefNo that's not correct it will give result with space,to get that result have to use
sep=''
.>>> print('abc','def') abc def >>> print('abc','def', sep='') abcdefBut to talk about what to do,so is
string formatting
the way to go,as @wavic show over.Using
+
can get very ugly soon in a longer string.>>> s_1 = 'bad' >>> s_2 = 'way' >>> answer = 42 >>> print('This is a ' + s_1 + ' ' + s_2 + ' to do string formatting' + ' and answer is ' + str(answer)) This is a bad way to do string formatting and answer is 42So in Python 3.6 got
f-string
,so if have that version use it.>>> s_1 = 'good' >>> s_2 = 'way' >>> answer = 42 >>> print(f'This is a {s_1} {s_2} to do string formatting and answer is {answer}') This is a good way to do string formatting and answer is 4210-year a ago in version 2.6 we got
.format()
,lower version than 3.6 use this.>>> s_1 = 'good' >>> s_2 = 'way' >>> answer = 42 >>> print('This is a {} {} to do string formatting and answer is {}'.format(s_1, s_2, answer)) This is a good way to do string formatting and answer is 42
classmates = {'Tony': 'cool but smells', 'Emma': 'sits behind me', 'Lucy': 'asks too many questions'} for k, v in classmates.items(): print(f'<{k}> --> {v}')
Output:<Tony> --> cool but smells
<Emma> --> sits behind me
<Lucy> --> asks too many questions