Python 2.7.12- How to have the same length for a new string as well as letters? -


i've started learning python 2.7.12 , in first homework given string called str2, , i'm supposed create string same length previous one. in addition,i need check third letter (if it's upper need convert lower , opposite, if it's not letter, need change '%'). other characters of first string should copied second one.

we given basic commends , nothing else can't solve it. please me! :)

it sounds want copy of word need change 3rd character. that's problem because strings immutable in python can't change character. trick copy string can change.

tmp = list(str2) 

then, need figure out how information character check it. turns out there several useful methods on string objects:

>>> dir('some string') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',  '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',  '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',  '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',  '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',  'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',  'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal',  'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',  'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',  'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',  'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',  'translate', 'upper', 'zfill'] 

so use them update value

>>> if tmp[2].isupper(): ...     tmp[2] = tmp[2].lower() ... elif tmp[2].islower(): ...     tmp[2] = tmp[2].upper() ... elif tmp[2].isdigit(): ...     tmp[2] = '%' ...  

and make more compact

>>> tmp[2] = (tmp[2].lower() if tmp[2].isupper()     else tmp[2].upper() if tmp[2].islower()     else '%' if tmp[2].isdigit else tmp[2]) 

finally, put together

>>> str3 = ''.join(tmp) 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -