User avatar
RaspbianUser1
Posts: 204
Joined: Thu Mar 05, 2020 6:34 pm

How can I shorten variable data

Thu Apr 02, 2020 11:54 am

I was just wondering how can I shorten data thats being saved in variables for example I want it to be like

Code: Select all

firstname =Ben
letter1= code......
print("The first letter in your name is",  letter1)

the output would be "B" in this case 
Running Raspberry Pi OS Full, therefore my comments will be based on that
Using RPI-4B 4GB at 2.1GHz CPU and 700MHz GPU
don't format your sd because someone said so.
Or put your favourite cutlery into your nearest outlet (May result in death) ;)

Garvan
Posts: 41
Joined: Sun Jan 05, 2020 9:59 am

Re: How can I shorten variable data

Thu Apr 02, 2020 12:13 pm

Code: Select all

firstname = "Ben"
letter1= firstname[0]
print("The first letter in your name is",  letter1)

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: How can I shorten variable data

Thu Apr 02, 2020 1:04 pm

To expand on Garvan's answer, as well as being able to pick a character from a string you can also get multiple characters, this is called slicing.

This gets the first character (we start counting at zero)

Code: Select all

>>> myString = "Hello World"
>>> print(myString[0])
H
This gets characters 0 and 1 (stopping at 2)

Code: Select all

>>> myString = "Hello World"
>>> print(myString[0:2])
He
It can get every second letter

Code: Select all

>>> print(myString[0:8:2])
HloW
You can even tell it to backwards

Code: Select all

>>> myString = "Hello World"
>>> print(myString[::-1])
dlroW olleH
Works for lists as well as strings.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
RaspbianUser1
Posts: 204
Joined: Thu Mar 05, 2020 6:34 pm

Re: How can I shorten variable data

Thu Apr 02, 2020 8:20 pm

yep that clears it up thanks for the help :)
Running Raspberry Pi OS Full, therefore my comments will be based on that
Using RPI-4B 4GB at 2.1GHz CPU and 700MHz GPU
don't format your sd because someone said so.
Or put your favourite cutlery into your nearest outlet (May result in death) ;)

Return to “Python”