0
How do I make python treat individual characters in a string like a variable?
So basically: a = 'z' word = input() How do I make it so that when the user inputs something like abcd it turns into zbcd?
6 ответов
+ 9
i keyboard smash a lot hahahahhwhaha easiest way is to use the replace()
'a' represents what you want to replace and 'z' is what to replace the letter 'a'
new_word = word.replace("a", "z" )
+ 10
we could also use a very similar solution like from Tibor Santa , but using 2 string methods *maketrans* and *translate*:
inp = input()
table = str.maketrans({'a':'z', 'r':'R', 'r':''})
res = ''.join([i.translate(table) for i in inp])
print(res)
+ 7
You can transform each character of a string and combine the result to a new string, using the join method with a list comprehension syntax.
For example you can build a mapping in a dictionary that changes one character to another. But you could also write a more complicated function that takes a character as input, and returns a different one.
word = 'sololearn'
switch = {'s': 'Y', 'r': ''}
changed = ''.join(switch.get(c, c) for c in word)
print(changed)
In this example the small s is replaced by capital Y, and the r is removed (replaced by an empty string).
The get method of the dictionary takes two parameters in this case, the first one is the key to look up, the second one is the default value when the key is not there. So it will replace only those characters which exist in the 'switch' dictionary.
+ 5
Automatically? probably impossible. If it were supported, then it can be a user rights violation. When your code tampers with user input mechanism in a way that it changes what user type; with or without their consent, it still doesn't sound right.
Manually, you can follow BroFar's suggestion, it's completely safe ..
+ 4
i keyboard smash a lot hahahahhwhaha if you want to do this without using replace() you can always loop through the word or phrase character / letter one by one
nword=""
yword = "antidisestablishmentarianism"
for l in yword:
if l == 'a':
x = 'z'
l = x
nword += l
print(nword)
+ 1
word = 'z' + input()[1:]
print(word)