xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to use variable in Python String All In One

How to use the variable in Python String All In One

如何在 Python 字符串中使用变量

#!/usr/bin/env python3
# coding: utf8

arr = [1, 2, 3]

for i in range(len(arr)):
  print("arr[i] =", i , arr[i])

print("\n")

for i in range(len(arr)):
  print("arr[{}] =".format(i), i , arr[i])

image

image

Python online REPL

https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3

errors ❌

#!/usr/bin/env python3
# coding: utf8

import board
import neopixel
from time import sleep

# 60 LEDs
pixels = neopixel.NeoPixel(board.D18, 60)

def red_led_strip():
  for x in range(0, 60):
    pixels[x] = (255, 0, 0)
    sleep(0.1)
    # ❌
    print("pixels[x] =", x, pixels[x])

def clear_buffer():
  for x in range(0, 60):
    pixels[x] = (0, 0, 0)

try:
  red_led_strip()
except KeyboardInterrupt:
  print('Ctrl + C exit ✅')
except RuntimeError as error:
  print("error =", error, error.args[0])
  pass
except Exception as error:
  print("exception =", error)
  raise error
finally:
  print("after three seconds, auto clear buffer! 👻")
  sleep(3.0)
  # cleanup
  clear_buffer()
  print('clear 🚀')


"""
$ chmod +x ./led-strip.py
# ❌ Can't open /dev/mem: Permission denied
# $ ./led-strip.py

# ✅
$ sudo ./led-strip.py
"""

image

solutions

#!/usr/bin/env python3
# coding: utf8

import board
import neopixel
from time import sleep

# 60 LEDs
pixels = neopixel.NeoPixel(board.D18, 60)

def red_led_strip():
  for x in range(0, 60):
    pixels[x] = (255, 0, 0)
    sleep(0.1)
    # ✅
    print("pixels[{}] =".format(x), x, pixels[x])

def clear_buffer():
  for x in range(0, 60):
    pixels[x] = (0, 0, 0)

try:
  red_led_strip()
except KeyboardInterrupt:
  print('Ctrl + C exit ✅')
except RuntimeError as error:
  print("error =", error, error.args[0])
  pass
except Exception as error:
  print("exception =", error)
  raise error
finally:
  print("after three seconds, auto clear buffer! 👻")
  sleep(3.0)
  # cleanup
  clear_buffer()
  print('clear 🚀')


"""
$ chmod +x ./led-strip.py
# ❌ Can't open /dev/mem: Permission denied
# $ ./led-strip.py

# ✅
$ sudo ./led-strip.py
"""

image

demos

$ chmod +x ./led-strip.py
# ❌ Can't open /dev/mem: Permission denied
# $ ./led-strip.py

# ✅
$ sudo ./led-strip.py

https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel/issues/151#issuecomment-1572096327

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

Python 字符串插值 All In One

Python 字符串中使用变量的 5 种方式

https://www.cnblogs.com/xgqfrms/p/16596326.html

https://www.freecodecamp.org/news/python-print-variable-how-to-print-a-string-and-variable/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-06-01 23:04  xgqfrms  阅读(8)  评论(0编辑  收藏  举报