Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Second Word in a Python 3 String

Tags:

python

string

I am trying to make a terminal in python, in which I can enter commands and have the program execute certain actions. I want to assign a variable to the string I get from an input like so :

cmd = input("Enter your command:")

Lets say I'm trying to make a Logging Command, where I would type out log primary {text} (which would store a string in a primary dictionary) or log secondary {text} (which would store the string in a secondary dictionary).

I want to be able to assign a variable to the second word in the command string. When I type log primary, I want to assign a variable to the word primary only.

In another words, how do I assign a variable to the second and third words of a string?

like image 253
Coolsugar Avatar asked Jul 18 '26 08:07

Coolsugar


2 Answers

var = cmd.split(" ")[1]

Here we are just splitting the string into an list and the criteria is " " (space) then its just indexing through the list.

Thats it !

like image 166
zro404 Avatar answered Jul 19 '26 22:07

zro404


You can enter:

cmd = input('Enter command:')
dictionary = cmd.split(' ')[1]
text = cmd.split(' ')[2:]

The dictionary variable will have the dictionary name, and text will have the text you want passed into the dictionary.

PS: the split command splits a string at certain characters. For example:

text = 'Hello world!'
text = text.split('o')
print(text)

will print:

['hell', ' w', 'rld!']
like image 36
TheFlyingTechie Avatar answered Jul 19 '26 21:07

TheFlyingTechie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!